Link to home
Start Free TrialLog in
Avatar of ProjectZIG

asked on

Check if a socket in Windows is connected or not

Hey guys,

  I have a DLL that opens a socket connection, and handles everything.  I have another DLL set up, called from the same program, that I would like to pass the socket to and have it check to see if the socket is still connected or not.

  Something like this:
  SOCKET sock; other work, such as connect, etc...
  int ret = isSocketConnected(sock);

  And have the return code be a negative number if the socket isn't connected anymore, and anything other than a negative number if the socket IS connected and there are no existing errors.  If possible, I want to do this without recv() as I want to leave the data in the pipe, so my program can handle it.  This will simply be to check and see if the socket is still connected, so I can re-connect if needed.

  Is this possible?

Avatar of sjklein42
Flag of United States of America image

You might be able to use getsockname() and check for SOCNOTCONN or a zero address.
Avatar of Narendra Kumar S S
This can be achieved by implementing KeepAlive messages.
telnet and many other network applications use the method of KeepAlives to check if the connection is active and also use that to tell the server that client is active.

You can search for KeepAlive for sockets and will find many pages.
Avatar of jkr
Flag of Germany image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can check if your still connected using a function like this. For the rest if the sockopt flags go here:

BOOL IsConnected(Socket s)
        int optval;
        Int optlen = sizeof(optval);
        // SO_ERROR is key here as it allows you to check the socket for errors and return a response. This is also cross platform compatible ;)
        int res = getsockopt(s,
        //Check the value here. If it fails you either had a connection reset(close) or error of sort.
        if(optval==0 && res==0) return true;
        return false;
Avatar of ProjectZIG


THanks, works perfectly