开发者

Same socket getting created

开发者 https://www.devze.com 2023-01-03 07:15 出处:网络
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

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 a开发者_如何学运维ddress 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.


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消