gpt4 book ai didi

c - 有没有办法用 C ping 一个特定的 IP 地址?

转载 作者:太空狗 更新时间:2023-10-29 16:37:41 24 4
gpt4 key购买 nike

有什么办法可以用 C ping 一个特定的 IP 地址吗?如果我想用一定数量的 ping 来 ping “www.google.com”,或者就此而言,一个本地地址,我需要一个程序来做到这一点。如何从 C ping?

最佳答案

目前还没有公认的答案,我在尝试完全按照此处提出的要求时偶然发现了这个问题,所以我想引用 Aif's回答here .
以下代码基于他的示例,在子进程中 ping 谷歌的公共(public) DNS,并在父进程中打印输出。

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

关于c - 有没有办法用 C ping 一个特定的 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8189935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com