有没有办法用 C ping 一个特定的 IP 地址? [英] Is there any way to ping a specific IP address with C?

查看:29
本文介绍了有没有办法用 C ping 一个特定的 IP 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用 C ping 一个特定的 IP 地址?如果我想用一定数量的 ping 或本地地址来 ping www.google.com",我需要一个程序来做到这一点.我如何从 C ping 通?

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?

推荐答案

目前还没有公认的答案,我在尝试完全按照此处提出的要求进行操作时偶然发现了这个问题,因此我想参考 Aif 的 答案此处.
以下代码基于他的例子,在子进程中ping Google的公共DNS,在父进程中打印输出.

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;
}

这篇关于有没有办法用 C ping 一个特定的 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆