Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to ping a specific IP address with C?

Is there any way to ping a specific IP address with C? If I wanted to ping "www.google.com" with a certain number of pings, or for that matter, a local address, I would need a program to do that. How can I ping from C?

like image 306
user1054683 Avatar asked Nov 18 '11 22:11

user1054683


People also ask

What is C in ping?

-c. Specifies the number of packets. This option is useful when you get an IP trace log. You can capture a minimum of ping packets.

How do I do a continuous ping in cmd?

Use the command "ping 192.168. 1.101 -t" to initiate a continuous ping. Again, replace the IP address with one specific to your device as needed. The -t can be placed before or after the IP address.


2 Answers

There is no accepted answer yet and I stumbled upon this question while trying to do exactly what was asked here so I wanted to refer to Aif's answer here.
The following code is based on his example and pings Google's public DNS in a child process and prints the output in the parent process.

#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

#define BUFLEN 1024

int main(int argc, char **argv)
{
    int pipe_arr[2];
    char buf[BUFLEN];

    //Create pipe - pipe_arr[0] is "reading end", pipe_arr[1] is "writing end"
    pipe(pipe_arr);

    if(fork() == 0) //child
    {
        dup2(pipe_arr[1], STDOUT_FILENO);
        execl("/sbin/ping", "ping", "-c 1", "8.8.8.8", (char*)NULL);    
    }
    else //parent
    {
        wait(NULL);
        read(pipe_arr[0], buf, BUFLEN);
        printf("%s\n", buf);

    }

    close(pipe_arr[0]);
    close(pipe_arr[1]);
    return 0;
}
like image 195
Leo Rohr Avatar answered Sep 20 '22 14:09

Leo Rohr


You could craft your own ICMP packets using raw sockets, but that's far from trivial. The source code for ping(1) is a good place to start on figuring out how to do that (it uses a BSD-like license; see the source code for the full license). Keep in mind that raw sockets require root privileges on Linux, so your program will need to be setuid root.

Of course, it's much easier to shell out to the ping(1) executable and not have to deal with any of this yourself. You won't have to worry about code licensing, and your program won't need root privileges (assuming it doesn't already need them for something else). system(3), popen(3), and fork(3)/exec(3) are your friends.

like image 41
Adam Rosenfield Avatar answered Sep 21 '22 14:09

Adam Rosenfield