ping(1)

/*


ping program for learning IP protocol


    author: jeff
    date:    2014/10/25

*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

static int ICMP_create();
static int opt_set(int sockfd);

int
main(int argc, char* argv[])
{
    int sockfd = ICMP_create();
    int optset = 0;
    if(sockfd != -1)
        printf("create socket ICMP success!
");
    else
        printf("create socket ICMP failed [%d]!
", errno);

    optset = opt_set(sockfd);
    if(optset != -1)
        printf("sock set success
");
    else
        printf("sock set failed
");
        
    return 0;
}


static int ICMP_create()
{
    return socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
}

static int opt_set(int sockfd)
{
    int on =1;
    return setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on));    
}
原文地址:https://www.cnblogs.com/unixshell/p/4050254.html