- 论坛徽章:
- 0
|
socket绑定错误
- ///////////////////////////////////////////////////////////////////////////////
- // 功能说明 : 初始化SOCKET 服务进程(TCP Server)
- // 输入参数 : nListenPort
- // 输出参数 : VOID
- // 返回值 : int
- // 使用说明 :
- ///////////////////////////////////////////////////////////////////////////////
- int CSocket::StartTcpListen ( int nListenPort, int nQueueSize )
- {
- int opt = 0; //
- int nListenFd; // 侦听句柄,接收侦听的句柄
- struct sockaddr_in sinLocalAddr; // 本进程的地址
- if ( (nListenFd=socket(AF_INET,SOCK_STREAM,0)) ==-1 )//建立侦听套接口
- return -1;
-
- bzero ( &(sinLocalAddr), sizeof(sinLocalAddr) );
- sinLocalAddr.sin_family = AF_INET;
- sinLocalAddr.sin_port = htons(nListenPort);
- sinLocalAddr.sin_addr.s_addr = INADDR_ANY;
- setsockopt ( nListenFd, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(int) );
- if( bind( nListenFd,(struct sockaddr*)&sinLocalAddr,sizeof(struct sockaddr) ) == -1 )
- {
- Close ( nListenFd );
- printf ( "bind %d fail, error %s\n", nListenPort, strerror(errno) );
- return -1;
- }
-
- if ( nQueueSize <= 0 )
- nQueueSize = 5;
-
- if( listen(nListenFd,nQueueSize) == -1 ) // 请注意系统核心最大监听队列默认为5
- {
- Close ( nListenFd );
- printf ( "listen fail, error %s\n", strerror(errno) );
- return -1;
- }
- return nListenFd;
- }
复制代码
虽然如此,有时还是会绑定失败的. |
|