In Chapter 4, paragraph 4.3 of Steven's "The Socket: Networking API, Third Edition", the author states the following
If connect fails, the socket is no longer usable and must be closed. We cannot call connect again on the socket.
Does anyone know the reason behind the above statement?
In my own experiments, i wrote a simple TCP client, that would run on host A and a simple TCP server, that would run on host B. The TCP client would attempt to connect to the TCP server on Host B forever.
So, I started the server on host B. Pulled the network wire from the host. Then I started the client on host A. After about 9 unsuccessful connect attempts on the same socket, I simply plugged the network wire back into the server host. The client connected successfully and happily sends messages at 80K/sec.
In yet another experiment, I pulled the wire from the server host, after a initial successful connect and few million messages exchanges after. Then, after few minutes, I connected the wire and message flow resumed on the same socket.
What happens when a socket connect() procedure is called/invoked? This causes the client to reach out to a TCP server to establish a connection between that client and the server. If there is already one or more servers on this connection, this new server will also be added to this connection.
The connect() call on a stream socket is used by the client application to establish a connection to a server. The server must have a passive open pending. A server that is using sockets must successfully call bind() and listen() before a connection can be accepted by the server with accept().
Because the initial socket is used to wait for communication while the second is used to communicate.
RETURN VALUEUpon successful completion, connect() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.
POSIX 2001 says in an informative section:
If
connect()
fails, the state of the socket is unspecified. Conforming applications should close the file descriptor and create a new socket before attempting to reconnect.
So the passage you quote is congruent with this specification. The fact it works on your machine does not mean your program is portable.
This may be rooted in the manpage of connect, where it says:
Generally, connection-based protocol sockets may successfully
connect()
only once; connectionless protocol sockets may useconnect()
multiple times to change their association.
That would imply that you cannot just re-connect a connection-based (read, TCP) socket. However, I cannot see it saying anything about a failing connect()
implying we cannot recycle the FD.
Resuming connections if the connection got interrupted is a feature of TCP, which will generally try to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With