0

I am trying to write an application that communicates with a server via Sockets on windows. I need a reliable way of telling if the connection is interrupted, for example by internet connectivity issues etc. I do not mean the return of connect(), but while the socket has already been esablished.So far the only one that was supposed to work was to send a message to the server with

int issocketclosed = send(socketFd," \b",3,0);

My integer however does not change when the connection gets killed. On the server side i am using "netcat -k -lv PORT" to listen for the connection and to simulate interruption i am CTRL-C -ing netcat .

My Socket code looks something like this:

WSADATA wsa;
WSAStartup(MAKEWORD(2,2),&wsa);
HANDLE s = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in connect_info;
connect_info.sin_family = AF_INET;
connect_info.sin_port = htons( port );
connect_info.sin_addr.s_addr = inet_addr(ipaddr);
connect(s,(struct sockaddr*)&connect_info,sizeof(connect_info));
while(1){

  Sleep(5000); //Do Stuff with socket

  int issocketclosed = send(socketFd," \b",3,0); //Check for connectin error
  if(issocketclosed == -1){
    connect(s,(struct sockaddr*)&connect_info,sizeof(connect_info)); // Reconnect
  }
}

I know this is not the first time this question has been asked but i have tried the other ones such as getsocketopt() without success. Any help is appreciated!

1 Answers1

1
  1. send() will eventually return -1 when sending over a connection that has been terminated by the peer, but due to socket buffering it won't happen on the first send() after the disconnect.
  2. recv() will return zero on a cleanly closed connection, or -1 on an aborted one.
  3. You can't reconnect a socket. You have to close it, create a new one, and connect that.
  4. You aren't checking for errors on socket() or connect(). You must check the result of every system call for -1, and print or log errno or perror() or strerror() when you get it, so you know what the actual error was.
user207421
  • 305,947
  • 44
  • 307
  • 483