//描述:具有超时功能的Socket连接函数 int ConnectHost(SOCKET& skt, const char* pszIp, int iPort, int iTimeoutMs) { bool fConnectOk = false; SOCKET m_skt = socket(AF_INET, SOCK_STREAM, 0); if ( m_skt != INVALID_SOCKET ) { struct sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_addr.S_un.S_addr = inet_addr(pszIp); sa.sin_port = htons(iPort); memset(sa.sin_zero, 0, sizeof(sa.sin_zero)); // 设为非阻塞模式 u_long cmd_value = 1; ioctlsocket(m_skt, FIONBIO, &cmd_value); if ( 0 == connect(m_skt, (struct sockaddr *)&sa, sizeof(struct sockaddr)) ) { fConnectOk = true; } else { fd_set set; FD_ZERO(&set); FD_SET(m_skt, &set); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = iTimeoutMs*1000; if ( select(NULL, NULL, &set, NULL, &timeout) > 0 ) { fConnectOk = true; } } // 设为阻塞模式 cmd_value = 0; ioctlsocket(m_skt, FIONBIO, &cmd_value); if ( fConnectOk ) //连接成功 { skt = m_skt; return 0; } } if ( m_skt != INVALID_SOCKET ) { closesocket(m_skt); m_skt = INVALID_SOCKET; } skt = INVALID_SOCKET; return -1; }