分类: C/C++
2008-12-10 11:11:03
/*此函数实现判断m_server的m_port端口是否可以连上,超时限制为nTimeOut秒*/ BOOL ConnectTest(char * m_server,int m_port) { struct hostent* host = NULL; struct sockaddr_in saddr; unsigned int s = 0; BOOL ret; time_t start; int error; host = gethostbyname (m_server); if (host==NULL)return FALSE; saddr.sin_family = AF_INET; saddr.sin_port = htons(m_port); saddr.sin_addr = *((struct in_addr*)host->;h_addr); if( (s=socket(AF_INET, SOCK_STREAM, 0))<0){ return FALSE; } fcntl(s,F_SETFL, O_NONBLOCK); if(connect(s,(struct sockaddr*)&saddr, sizeof(saddr)) == -1) { if (errno == EINPROGRESS){// it is in the connect process struct timeval tv; fd_set writefds; tv.tv_sec = m_nTimeOut; tv.tv_usec = 0; FD_ZERO(&writefds); FD_SET(s, &writefds); if(select(s+1,NULL,&writefds,NULL,&tv)>;0){ int len=sizeof(int); //下面的一句一定要,主要针对防火墙 getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &len); if(error==0) ret=TRUE; else ret=FALSE; }else ret=FALSE;//timeout or error happen }else ret=FALSE; } else ret=TRUE; close(s); return ret; } |