我的任务是检查IP是否还活着。因此,我遵循这个link并修改了代码,如下所示..。
int isServerAlive(const char* serverAdd)
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(65432); // Could be anything.
inet_pton(AF_INET, serverAdd, &sin.sin_addr);
if (connect(sockfd, (struct sockaddr *) &sin, sizeof(sin)) == -1)
{
// The two main errors you get if the host is dead are ENETUNREACH and ETIMEDOUT.
if (errno == ENETUNREACH || errno == ETIMEDOUT)
{
printf("Error connecting %s: %d (%s)\n",serverAdd, errno, strerror(errno));
return FAILURE;
}
}
return SUCCESS;
}当我试图执行这段代码时,连接调用要花费太多的时间。
提前谢谢。
发布于 2016-11-18 07:07:47
发布于 2016-11-18 08:49:18
如果您知道服务器将响应ping,则绝对应该使用ping进行检测。假设您的服务器在代理或NAT后面,这很容易击败您的SYN检测。
在Linux环境中,ping检测机制应该如下所示:
system("ping xx.xx.xx.xx -c 3 -i 1 -W 3 -q > /tmp/ping-xx.xx.xx.xx.log &");
6秒后,您可以打开文件,并解析ping结果:
发送3包,0接收,100%丢包,时间2039 100
Note:
-c 3: only issue 3 ping packets
-i 1: send packets at 1 second interval
-W 3: wait response up to 3 seconds, so the total time should no more than 3 + 3 = 6 seconds
-q: suppress no needed information.这些ping参数仅以服务器为例,您应该根据实际环境定制它们。
https://stackoverflow.com/questions/40671180
复制相似问题