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;
  ..do 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?

CInternet ProtocolsWindows Networking

Avatar of undefined
Last Comment

8/22/2022 - Mon

You might be able to use getsockname() and check for SOCNOTCONN or a zero address.
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.

View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.

You can check if your still connected using a function like this. For the rest if the sockopt flags go here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms738544(v=vs.85).aspx

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;
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck

THanks, works perfectly