0

I'm writing a TCP client using asynchronous calls. If the server is active when the app starts then it connects and talks OK. However if the first connect fails, then every subsequent call to connect() fails with WSAENOTCONN(10057) without producing any network traffic (checked with Wireshark).

Currently the code does not close the socket when it gets the error. The TCP state diagram does not seem to require it. It simply waits for 30 seconds and tries the connect() again.

That subsequent connect() and the following read() both return the WSAENOTCONN error.

Do I need to close the socket and open a new one? If so, which errors require me to close the socket, since there are a lot of different errors, some of which I will probably never see on the test bench.

You can assume this is MS Winsock2, although it is actually Interval Zero RTX 2009, which is subtly different in some places.

2 Answers2

1

Do I need to close the socket and open a new one?

Yes.

If so, which errors require me to close the socket, since there are a lot of different errors, some of which I will probably never see on the test bench.

Almost all errors are fatal to the connection and should result in you closing the socket. EAGAIN/EWOULDBLOCK s a prominent exception, as is EINTR, but I can't think of any others offhand.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • EINVAL isn't fatal to the connection either, and EBADF as well, but the program almost certainly isn't going to be able to continue in either case as both these indicate software bugs. – user207421 Jan 05 '17 at 17:59
  • According to Winsock's [documentation](https://msdn.microsoft.com/en-us/library/windows/desktop/ms737625.aspx): "*If the error code returned indicates the connection attempt failed (that is, WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT) **the application can call connect again for the same socket**.*" I would not (and do not) rely on that, though. It is best to close and recreate the socket on any **connection-related** error. – Remy Lebeau Jan 05 '17 at 19:53
  • @RemyLebeau Agreed. That's a Winsock-ism that doesn't work in BSD sockets in BSD or Linux implementations. – user207421 Jan 06 '17 at 09:31
0

Do I need to close the socket and open a new one?

Yes.

You should close the socket under all error conditions that results in connection gone for good (Say, like the peer has closed the connection)

Prabhu
  • 3,443
  • 15
  • 26