linux下c语言判断指定IP能否ping通的测试程序

一个简单的测试demo,可按需修改:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

/*ping通返回0,ping不通一直等待*/

int go_ping(char *svrip)

{
        int time=0;
        while(1)
        {
                pid_t pid;
                if ((pid = vfork()) < 0)
                {
                        printf("\nvfork error\n");
                        return 0;
                }
                else if (pid == 0)
                {       
                        if ( execlp("ping", "ping","-c","1",svrip, (char*)0) < 0)
                        {
                                printf("\nexeclp error\n");
                                return 0;
                        }
                }

                int stat;
                waitpid(pid, &stat, 0);
                if (stat == 0)
                {
                        printf("ping ok\n");
                        return 0;
                }
                if(time++>10 )
                        printf("error\n");
                sleep(1);
        }
        return 0;
}
int main()
{
        go_ping("192.168.1.11");

        return 0;
}

猜你喜欢

转载自blog.csdn.net/zhangb98/article/details/118569691