int check(void)
{
char buf[512] = {0};
FILE *fp = NULL;
int i = 0;
char gateway_ip[32] = {0};
char buf1[128] = {0};
fp = popen("route -n | grep UG |awk '{print $2}'","r"); //执行route 获取网关的ip
fgets(gateway_ip, 32, fp);
pclose(fp);
printf("gateway_ip : %s, len : %d\n",gateway_ip,strlen(gateway_ip));
if(strlen(gateway_ip) < 7)
{
printf("len < 7\n");
return -1;
}
if(gateway_ip[0] == 0)
{
printf("gateway_ip[0] == 0\n");
return -1;
}
if(gateway_ip[0] == '\n')
{
printf("gateway_ip[0] == n \n");
return -1;
}
if(gateway_ip[0] == '\r')
{
printf("gateway_ip[0] == r \n");
return -1;
}
gateway_ip[strlen(gateway_ip) - 1] = 0;//clear \n
sprintf(buf1, "ping -c 4 -W 5 %s",gateway_ip); //组成ping网关的命令
for(i = 0; i < 2; i++) //连续尝试2次
{
fp = popen("ping -c 4 -W 5 8.8.8.8","r"); //执行ping 谷歌dns服务器的ip,为什么不是ping www.google.com ? 下面会说明
if(fp)
{
memset(buf, 0x0, sizeof(buf));
fread(buf, 510, 1, fp);
pclose(fp);
fp = NULL;
if((strstr(buf, "time=") != NULL) && (strstr(buf, "ttl=") != NULL)) //如果命令返回的字符串中包含time=和ttl=就说明ping成功了
{
return 0; //返回0表示互联网畅通
}
}
fp = popen(buf1,"r"); //执行ping网关的指令,测试和路由器连接是否畅通
if(fp)
{
memset(buf, 0x0, sizeof(buf));
fread(buf, 510, 1, fp);
pclose(fp);
fp = NULL;
if((strstr(buf, "time=") != NULL) && (strstr(buf, "ttl=") != NULL))
{
return 1; //如果ping网关成功返回1说明路由器只有路由器时通的
}
}
}
return -1; //连续尝试2次后返回错误表示和路由器之间的连接都不通
}
上面代码中为何不去ping 谷歌的域名而是ping dns服务器的ip呢?这是因为ping域名的过程中首先要解析域名,如果网络不通,
域名解析的过程会卡住一段时间从而不能快速反应,ping ip则可以限定超时时间和尝试次数
ping -c 4 -W 5 指定尝试4次,每次的超时时间是5秒