如果给出不存在的 IP 地址,以下例程将超时,这很好。但是,如果 linux 系统(它正在运行)没有连接到 eth0 或 wlan0 上的任何网络,那么它就会挂起。即使网络再次连接到 eth0,仍然没有响应。即使没有连接到网络,有没有办法让超时应用?或者,是否可以事先进行检查以确定是否存在与网络的连接?谢谢。
int connect_to_host()
{
u_short port; /* user specified port number */
char *addr; /* will be a pointer to the address */
struct sockaddr_in address; /* the libc network address data structure */
short int sock = -1; /* file descriptor for the network socket */
fd_set fdset;
struct timeval tv;
int connected = 0;
port = 22;
addr = "192.168.2.5";
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
address.sin_port = htons(port); /* translate int2port num */
sock = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sock, F_SETFL, O_NONBLOCK);
connect(sock, (struct sockaddr *)&address, sizeof(address));
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
tv.tv_sec = 3; /* 10 second timeout */
tv.tv_usec = 0;
if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0) {
printf("%s:%d is open\n", addr, port);
connected = 1;
}
}
close(sock);
return connected;
}