Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

networking - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", buf);

    }

    close(pipe_arr[0]);
    close(pipe_arr[1]);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...