tags:

views:

127

answers:

1

I have created a socket using the following lines of code. Now i change the value of the socket i get like this

m_Socket++;

Even now the send recv socket functions succeeds without throwing SOCKET_ERROR. I expect that it must throw error.

Am i doing something wrong.

struct sockaddr_in ServerSock; // Socket address structure to bind the Port Number to listen to

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 the send recv socket functions succeeds without throwing SOCKET_ERROR. I expect that it must throw error.

Am i doing something wrong.

+9  A: 

It's because of the peculiar nature of Windows handles -- when created they are divisible by four and when used their two lowest bits are ignored. Incrementing a handle by one will make m_Socket refer to the same socket as before (only when you increment by four will the function return an error -- unless there is another handle with that value open).

You should not probe for open handles in this manner. While there are other ways to enumerate open handles, you shouldn't use them. Do not depend on the system to keep track of your handles -- track them yourself.

avakar
Good to know, I didn't know that. But still: Why on earth would you increment a *socket value*?
Iulian Şerbănoiu
@Iulian Şerbănoiu, you wouldn't.
avakar
@avakar This is great answer. I didnt know this scenario.
ckv