ckv
ckv

Reputation: 10820

Same socket getting created

I have this piece of code where a server socket is created and is set to listen on a particular port number say 5005. Now once the accept socket function returns the socket that gets created is copied into the m_Socket variable and finally i shutdown the server socket named SocServer which was created locally.

Now my question Is it possible that the SocServer(created initially) and m_Socket(copied when accept returns) get the same number say 1500.

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(PortNumber);//port number of 5005

    // To Create a socket for listening on PortNumber
    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
    m_Socket=accept(SocServer,(struct sockaddr*)&insock,&insocklen);
     //delete the server socket
     if(SocServer != INVALID_SOCKET)
    {
        //To close and shutdown the Socserver
        shutdown(SocServer, 2 );      
        closesocket(SocServer);
    }

is it possible that Socserver and m_socket are the same because

as per my code the socket connection is established and for some other reason it gets closed and in TCPView it shows established for a while and then no connection at all.

Note: This happens only in some machines and is not reproducible always. Can any other network related issue be the cause.

Upvotes: 0

Views: 186

Answers (2)

PeterK
PeterK

Reputation: 6317

Are you certain that the client who is connecting to your server did not close the connection? Also, you did not provide any function which uses the m_Socket so i cannot tell you if there is any problem while handling the incoming connection. I do not think that m_socket and SocServer may end up the same.

Upvotes: 2

anon
anon

Reputation:

In this code:

 m_Socket=accept(SocServer,(struct sockaddr*)&insock,&insocklen);
 if(SocServer != INVALID_SOCKET)

why do you call accept() with what may apparently be a bad socket? And do you test the value you get back from accept() anywhere?

Upvotes: 1

Related Questions