Tag Archives: The SOCKET communication. The C language

Socket error 10057 problem_ Error record

10057 is socket is not connected. Later, it was found that the socket was set as non-blocking before. When the connect tried to connect, the connection was not connected immediately returned, and TCP was still shaking hands for three times.
There are two other points to note about transplantation


problem:
1. The getsockopt implementation from Berkeley returns 0, and the error waiting for processing is returned in the variable errno; But Solaris will have getsockopt return -1 and errno set as the error to be handled; We have to deal with both cases;

2. Portability issues in platforms with different socket implementations when dealing with non-blocking connect. First, it is possible that the connection has already been established and the other party’s data has already arrived before the select call. In this case, when the connection succeeds, the socket will be both readable and writable. This is the same as if the connection failed. At this point we also have to read the error value through getsockopt

The simple code is as follows, for reference only:
BOOL ConnectServer(int robot_num)
{
char errnum[10] = {0};
int err = -1;
int error = -1;
int errlen = sizeof(error);
int no1 = robot_num;
fd_set wset;
struct timeval tm;
tm.tv_sec = 5;
tm.tv_usec = 0;
FD_ZERO(& wset);
FD_SET(sHost[no1],& wset);

// set server address
servaddr. sin_family =AF_INET;
servAddr. Sin_addr. S_addr = inet_addr (192.168.1.104, “”); //& IP [no1-1][0]
servaddr.sin_port = htons(6665); //atoi(& The port [no1-1] [0])

// connect server
retVal = connect (sHost [no], (LPSOCKADDR) & amp; servAddr, sizeof(servAddr));
err = WSAGetLastError();

if(SOCKET_ERROR == retVal)
{
{
if(WSAEWOULDBLOCK == err || WSAEINVAL == err) // there is no more non-blocking operation
{
if(select(0,NULL,&amp); wset,NULL,& tm) < = 0){// Error timeout or connection failure; Return 0, representing timeout
printf(“error code is %s\n”,strerror(errno));
closesocket(sHost[no1]);
}
if( ! FD_ISSET(sHost[no1],& Wset)){// If the value in the set, non-zero;
printf(“error code is %s\n”,strerror(errno));
closesocket(sHost[no1]);
}
getsockopt(sHost[no1],SOL_SOCKET,SO_ERROR,(char*)& error,& errlen);
if (error ! = 0)
{
printf(“Connect failed! \n”);
bConnecting = FALSE;
}else{
printf(“Connect successfully! \n”);
bConnecting = TRUE;
}
}else if (WSAEISCONN == err)// connection complete
{
printf(” connection complete \n”);

}else if (WSAENOTCONN == err)// connection not complete
{
printf(“socket is not connected \n”);

} else// for other reasons, the connection fails
{
printf (” connect err = % d \ n “, err); // trying an already in progress operation on a non-blocking socket
printf(” other reason, connection failed \n”);
}
}

if (retVal == 0)// successfully Connect
{
printf(“Connect successfully! \n”);
bConnecting = TRUE;
}
return bConnecting;
}