Socket sends recv functions

I created a socket using the following lines of code. Now I am changing the socket value that I get as

m_Socket ++;

Even now, send recv socket functions succeed without throwing SOCKET_ERROR. I expect him to throw an error.

I'm doing something wrong.

struct sockaddr_in ServerSock; // Socket address structure for binding the port number for listening

char *localIP ; SOCKET SocServer; //To Set up the sockaddr structure ServerSock.sin_family = AF_INET; ServerSock.sin_addr.s_addr = INADDR_ANY; ServerSock.sin_port = htons(pLantronics->m_wRIPortNo); // To Create a socket for listening on wPortNumber if(( SocServer = socket( AF_INET, SOCK_STREAM, 0 )) == INVALID_SOCKET ) { return FALSE; } //To bind the socket with wPortNumber if(bind(SocServer,(sockaddr*)&ServerSock,sizeof(ServerSock))!=0) { return FALSE; } // To Listen for the connection on wPortNumber if(listen(SocServer,SOMAXCONN)!=0) { return FALSE; } // Structure to get the IP Address of the connecting Entity sockaddr_in insock; int insocklen=sizeof(insock); //To accept the Incoming connection on the wPortNumber pLantronics->m_Socket=accept(SocServer,(struct sockaddr*)&insock,&insocklen); if(pLantronics->m_Socket == INVALID_SOCKET) { shutdown(SocServer, 2 ); closesocket(SocServer ); return FALSE; } // To make socket non-blocking DWORD dwNonBlocking = 1; if(ioctlsocket( pLantronics->m_Socket, FIONBIO, &dwNonBlocking )) { shutdown(pLantronics->m_Socket, 2); closesocket(pLantronics->m_Socket); return FALSE; } pLantronics->m_sModemName = inet_ntoa(insock.sin_addr); 

Now i do

 m_Socket++;//change to some other number ideally expecting send recv to fail. 

Even now, send recv socket functions succeed without throwing SOCKET_ERROR. I expect him to throw an error.

I'm doing something wrong.

+4
source share
1 answer

This is due to the specifics of Windows descriptors - when they are created, they are divided into four, and when used, the two least significant bits are ignored. Incrementing the descriptor one by one will make m_Socket reference to the same socket as before (only if you increase by four, the function will return an error - unless there is another descriptor with this value open).

You do not need to understand open handles this way. Although there are other ways to list public descriptors, you should not use them. Do not depend on the system to monitor your pens - track them yourself.

+13
source

Source: https://habr.com/ru/post/1312946/


All Articles