當前位置:編程學習大全網 - 網站源碼 - 如何使用C語言來判斷ping命令是否能ping通,求代碼。 要c的不要c++或c#的。

如何使用C語言來判斷ping命令是否能ping通,求代碼。 要c的不要c++或c#的。

代碼在 MAC OS 下運行良好,在 Linux 下得話需要稍作修改

#include?<stdio.h>

#include?<fcntl.h>

#include?<string.h>

#include?<stdlib.h>

#include?<unistd.h>

int?main(void)

{

char?host[256],?cmd[256];

printf("please?input?dest_host:");

scanf("%s",?host);

strncpy(cmd,?"ping?-c5?",?9);

strncat(cmd,?host,?strlen(host));

strncat(cmd,?"?>?ping.txt",?11);

pid_t?pid?=?fork();

if(pid?<?0)

{

printf("fork?error\n");

exit(-1);

}

if(pid==0)

{

if(execlp("/bin/sh",?"sh",?"-c",?cmd,?(char?*)0)?<?0)

printf("execlp?error\n");

exit(0);

}

if(waitpid(pid,?NULL,?0)?<?0)

printf("waitpid?error\n");

int?fd?=?open("ping.txt",?O_RDWR);

int?n;

char?buf[1024];

n?=?read(fd,?buf,?sizeof(buf));

if(n?<=?0)

{

printf("read?error\n");

exit(-1);

}

if(strstr(buf,?"100.0%")?==?NULL)

printf("can?reach?%s",?host);

else

printf("can't?reach?%s",?host);

close(fd);

return?0;

}

如果妳想要 ping 程序,剛好我最近寫了壹個,要的話私信

  • 上一篇:怎樣應用籌碼分布指標
  • 下一篇:Linux主要應用在哪些領域
  • copyright 2024編程學習大全網