Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing socket descriptor on connection failure

Tags:

c

linux

sockets

In my client code, I am following these steps to connect to a socket:

  1. Creating a socket

    sockDesc = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)  
    
  2. Connecting it (retry for 'x' time in case of failure)

    connect(sockDesc, (sockaddr *) &destAddr, sizeof(destAddr))  
    

    (After filling the destAddr fields)

  3. Using the socket for send()/recv() operation:

    send(sockDesc, buffer, bufferLen, 0)  
    recv(sockDesc, buffer, bufferLen, 0)  
    
  4. close() the socket descriptor and exit

    close(sockDesc)  
    

If during send()/recv() the connection breaks, I found that I could connect by returning to step 2.

Is this solution okay? should I close the socket descriptor and return to step 1?

Another interesting observation that I am not able to understand is when I stop my echo server and start the client. I create a Socket (step 1) and call connect() which fails (as expected) but then I keep calling connect(), lets say, 10 times. After 5 retries I start the server and connect() is successful. But during the send() call it receives SIGPIPE error. I would like to know:

1) Do I need to create a new socket every time connect() fails? As per my understanding as long as I have not performed any send()/recv() on the socket it is as good as new and I can reuse the same fd for the connect() call.

2) I don't understand why SIGPIPE is received when the server is up and connect() is successful.

like image 800
Adil Avatar asked Feb 10 '10 14:02

Adil


1 Answers

Yes, you should close and go back to step 1:

close() closes a file descriptor, so that it no longer refers to any file and may be reused.

From here.

like image 104
Hassan Syed Avatar answered Sep 29 '22 12:09

Hassan Syed