Sending ICMP packets in a C program

At first glance: You can't rely on time struct after select(). You should also set usec.

So in the code, include the specification of t values inside the for loop:

for (i = 1; i <= num; i++) {
    t.tv_sec = 5;
    t.tv_usec = 0;
    ...

Else when you get on second iteration t (can have) changed.

In your sprintf(src_ip, ...) and dst_ip you have omitted format.


In addition to ebutusov's reply:

ip->ip_sum = 0;
icmp->icmp_cksum = htons(~(ICMP_ECHO << 8));

Are both incorrect.
You need to calculate the checksum properly (it's the same algorithm for both, but covers different fields).


Just one thing that I've noticed...

You've got this:

 struct ip *ip = (struct ip *)send_buf;

Then, you are assigning destination field:

ip->ip_dst = (*(struct in_addr *)dst_hp->h_addr)

And then you are erasing it with memset (since send_buff points to the same thing):

memset(send_buf, 0, sizeof(send_buf));

So, when you are trying to get ip_dst here:

dst.sin_addr = ip->ip_dst;

you are getting 0 instead of what you set earlier.

Tags:

C

Ping

Icmp

Sendto