linux平台下的socket 通过设置超时时间可以在connect的时候进行超时判断,而windows设置超时对connect不起作用,默认大概是16s。
以下是windows平台下connect超时的示例代码。可以直接编译运行。
#include <Winsock2.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
bool connect(char *host, int port, int timeout=3)
{
TIMEVAL Timeout;
Timeout.tv_sec = timeout;
Timeout.tv_usec = 0;
struct sockaddr_in address; /* the libc network address data structure */
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
address.sin_addr.s_addr = inet_addr(host); /* assign the address */
address.sin_port = htons(port); /* translate int2port num */
address.sin_family = AF_INET;
//set the socket in non-blocking
unsigned long iMode = 1;
int iResult = ioctlsocket(sock, FIONBIO, &iMode);
if (iResult != NO_ERROR)
{
printf("ioctlsocket failed with error: %ld\n", iResult);
}
if (connect(sock, (struct sockaddr *)&address, sizeof(address)) == false)
{
return false;
}
// restart the socket mode
iMode = 0;
iResult = ioctlsocket(sock, FIONBIO, &iMode);
if (iResult != NO_ERROR)
{
printf("ioctlsocket failed with error: %ld\n", iResult);
}
fd_set Write, Err;
FD_ZERO(&Write);
FD_ZERO(&Err);
FD_SET(sock, &Write);
FD_SET(sock, &Err);
// check if the socket is ready
select(0, NULL, &Write, &Err, &Timeout);
if (FD_ISSET(sock, &Write))
{
return true;
}
return false;
}
using namespace std;
int main()
{
while (1)
{
bool ret = false;
ret = connect("www.baidu.com", 800);
if(ret )
{
printf("sucess\n");
}
else printf("failed\n");
ret = connect("192.168.1.200", 80);
if (ret)
{
printf("sucess\n");
}
else printf("failed\n");
}
return 0;
}
#ifdef WIN32
class WSInit
{
public:
WSInit()
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
}
~WSInit() { WSACleanup(); }
};
static WSInit wsinit_;
#endif
linux平台connect超时设置的示例:
参考http://ju.outofmemory.cn/entry/136595
经测试可以正常使用。简洁明了。
int connect_timeout_v3(int sock, struct sockaddr *addr, int timeout) {
int ret;
struct timeval timeo = {3, 0};
socklen_t len = sizeof(timeo);
ret = setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeo, len);
if (ret) {
printf("set socket opt failed!\n");
}
ret = connect(sock, addr, sizeof(struct sockaddr_in));
return ret;
}
引用:
https://www.codeproject.com/tips/168704/how-to-set-a-socket-connection-timeout
不得不说国内有些人真的是水平太差,错误代码也往网上放,https://blog.youkuaiyun.com/cupidove/article/details/43953603/
下面这个是有问题的:https://blog.youkuaiyun.com/cupidove/article/details/43953603/