Reusing socket descriptor on connection failure

后端 未结 5 603
逝去的感伤
逝去的感伤 2020-12-19 00:38

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_TC         
    
    
            
相关标签:
5条回答
  • 2020-12-19 01:09

    If the Single UNIX Specification doesn't say that it MUST work to go back to step #2 instead of step #1, then the fact that it happens to work on Linux is just an implementation detail, and you would be far better off and more portable if you go back to step #1. As far as I am aware, the specification does not make any guarantee that it is ok to go back to step #2 and, therefore, I would advise you to go back to step #1.

    0 讨论(0)
  • 2020-12-19 01:15

    I think closing the socket is the right thing to do, despite the fact that it may work if you don't.

    A socket which has failed to connect may not be in EXACTLY the same state as a brand new one - which could cause problems later. I'd rather avoid the possibility and just make a new one. It's cleaner.

    TCP sockets hold a LOT of state, some of which is implementation-specific and worked out from the network.

    0 讨论(0)
  • 2020-12-19 01:19

    If the connection was broken and you try to write on the file descriptor you should get the broken pipe error/signal. All this is saying is that the file descriptor you tried writing to no longer has anyone on the other side to read what you are sending.

    What you can do is catch the signal SIGPIPE and then deal with the reconnecting by closing the FD and going back to your step 1. You will now have a new FD you can read and write from for the connection.

    0 讨论(0)
  • 2020-12-19 01:22

    Sockets corresponding to broken connection is in unstable state. normally you will not be allowed to connect to again unless the operating system release the socket.

    I think it will be better to close() and connect again.. you don't have to create another socket.

    Anyway, make sure to set LINGER of your socket to ensure that no data is lost in transmision.

    See http://www.gnu.org/s/libc/manual/html_node/Socket_002dLevel-Options.html#Socket_002dLevel-Options

    0 讨论(0)
  • 2020-12-19 01:25

    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.

    0 讨论(0)
提交回复
热议问题