accept 返回 22 的错误,strerror为:Invalid argument, 救命呀,什么原因
大家帮忙看看:
#define SERVER_IP "10.3.144.212 "
#define SERVER_PORT "8012 "
int iServerFd=-1;
int gSerialNo=0;
int tcpListenProc (char *ip, char* port)
{
int listenSock = 0,
reuse_addr = 0;
if (!ip || !port)
{
return -2;
}
listenSock =socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in addr = {0};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip);
addr.sin_port = htons(atoi(port));
reuse_addr = 1;
if(setsockopt(listenSock, 1, SO_REUSEADDR,(char *)&reuse_addr,sizeof(reuse_addr)) < 0)
{
close(listenSock);
return -2;
}
if (bind(listenSock,(struct sockaddr*)&addr,sizeof(addr))==0 && listen(listenSock, 10)==0)
{
}
else
{
return -3;
}
return listenSock;
}
int main(int argc, char **argv)
{
int connFd;
socklen_t addrLen;
struct sockaddr_in clientAddr={0};
char buf[2048];
int ret = -1;
iServerFd = tcpListenProc(SERVER_IP, SERVER_PORT);
if ( iServerFd <0 )
{
printf( "iServerFd error. ret: %d\n ", ret);
}
printf( "iServerFd is %d\n ", iServerFd);
for( ; ; )
{
connFd = accept (iServerFd, (struct sockaddr *)&clientAddr, &addrLen);
if ( connFd <= 0 )
{
printf( "error no: %d, error string: %s\n ", errno, strerror(errno) );
continue;
}
else{
printf( "connFd is %d\n ", connFd);
snprintf(buf, sizeof(buf), "gSerialNo is %d\n ", gSerialNo);
printf( "-------[%s]\n ", buf);
Send(connFd, buf, strlen(buf), 3);
}
close(connFd);
}
return 0;
}
[解决办法]
在accept前面加上:
addrLen = sizeof(clientAddr);
MSDN上面关于这个的说明不是很好,应该对这个变量赋值