gpt4 book ai didi

c++ - connect() 超时不工作

转载 作者:行者123 更新时间:2023-11-28 00:31:40 25 4
gpt4 key购买 nike

我正在使用此代码连接到服务器,但它没有等待我设置的 10 秒超时。连接失败后立即返回。

BOOL Connect(string server, int port, int timeout)
{
struct sockaddr_in RemoteHost;
TIMEVAL Timeout;
Timeout.tv_sec = timeout;
Timeout.tv_usec = 0;
int con_error = 0;

#ifdef W32
WSADATA wsd;
if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
{
DEBUG(L"Failed to load Winsock!\n");
return FALSE;
}
#endif

//create socket if it is not already created
if (s == SOCKET_ERROR)
{
//Create socket
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == SOCKET_ERROR)
{
DEBUG(L"Could not create socket");
return FALSE;
}
}

//setup address structure
if (inet_addr(server.c_str()) == INADDR_NONE)
{
struct hostent *he;

//resolve the hostname, its not an ip address
if ((he = gethostbyname(server.c_str())) == NULL)
{
//gethostbyname failed
DEBUG(L"gethostbyname() - Failed to resolve hostname\n");
return FALSE;
}
}
else//plain ip address
{
RemoteHost.sin_addr.s_addr = inet_addr(server.c_str());
}

RemoteHost.sin_family = AF_INET;
RemoteHost.sin_port = htons(port);

//set the socket in non-blocking
unsigned long iMode = 1;
int iResult = ioctlsocket(s, FIONBIO, &iMode);
if (iResult != NO_ERROR)
{
DEBUGP(L"ioctlsocket failed with error: %ld\n", iResult);
return FALSE;
}

//Connect to remote server
if ((con_error=connect(s, (struct sockaddr *)&RemoteHost, sizeof(RemoteHost))) < 0)
{
if (con_error != EINPROGRESS)
{
DEBUG(L"connect() failed");
return FALSE;
}
}

// restart the socket mode
iMode = 0;
iResult = ioctlsocket(s, FIONBIO, &iMode);
if (iResult != NO_ERROR)
{
DEBUGP(L"ioctlsocket failed with error: %ld\n", iResult);
return FALSE;
}

fd_set Write, Err;
FD_ZERO(&Write);
FD_ZERO(&Err);
FD_SET(s, &Write);
FD_SET(s, &Err);

// check if the socket is ready
select(0, NULL, &Write, &Err, &Timeout);
if (FD_ISSET(s, &Write))
{
return TRUE;
}
return FALSE;
}

最佳答案

当套接字在目标系统上不可用时,它可能会发回 an ICMP message indicating that the socket is not open并尝试连接失败。在这种情况下,winsock 函数将立即返回 - 这是设计使然。

关于c++ - connect() 超时不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22660549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com