我们在编写网络通信程序的时候,不论作为Linux下回收异常断开的TCP连接》,但是倘若要及时检测网络连通性,不得不频繁地发
另外一种办法是在select
#include
#include
#include
#include
#include
int checkConnect(char *dst, int cnt)
{
int i = 0;
FILE *stream;
char recvBuf[16] = {0};
char cmdBuf[256] = {0};
if (NULL == dst || cnt <= 0)
return -1;
sprintf(cmdBuf, "ping %s -c %d -i 0.2 | grep time= | wc -l", dst, cnt);
stream = popen(cmdBuf, "r");
fread(recvBuf, sizeof(char), sizeof(recvBuf)-1, stream);
pclose(stream);
if (atoi(recvBuf) > 0)
return 0;
return -1;
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
printf("Please set the arguments as follow:\n");
printf("%s \n", argv[0]);
return -1;
}
if (checkConnect(argv[1], atoi(argv[2])))
printf("Network is not up to %s\n", argv[1]);
else
printf("Network is up to %s\n", argv[1]);
return 0;
}
上面提到的connect跟Ping封装虽然比keepLive更灵活,但仍然存在不足,对于
除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。