Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
929 views
in Technique[技术] by (71.8m points)

c - Does socket become unusable after connect() fails?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...