有没有办法用C ping特定IP地址?

问题描述 投票:13回答:4

有没有办法用C ping特定IP地址?如果我想使用一定数量的ping命令来ping“ www.google.com”,或者就此而言,使用本地地址,则需要一个程序来执行此操作。如何从C ping?

c networking ip-address
4个回答
11
投票
#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; }

9
投票
当然,将外壳程序打包到ping(1)可执行文件要容易得多,不必亲自​​处理。您不必担心代码许可,您的程序不需要root特权(假设它不需要其他特权)。 ping(1)system(3)system(3) / popen(3)是您的朋友。

4
投票

2
投票
© www.soinside.com 2019 - 2024. All rights reserved.