1
votes

I am trying to connect to a server on another machine via a non-blocking connect().

However, when I do so, Connect() returns -1, and I receive WSAEWOULDBLOCK from WSAGetLastError().

MSDN Documentation states that: It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established (reference).

The issue is that I am always receiving the error, and -1 is returned from connect() EVEN IF my server is not running.

My socket is a SOCK_STREAM socket, just as suggested. How might I remedy this? Should I provide a timeout after the connect() call to ensure that enough time is given for connect to establish a connection?

1
If you try to connect to a non-existing server, it may indeed block for quite some time. There are always some network communication going on even when connecting to a non-existing server or a server port that's not open. See the TCP 3-way handshake to understand what happens on connection establishment. - Some programmer dude
You can use select() to block until the connect is done. - brian beuning

1 Answers

2
votes

Use ConnectEx and pass the OVERLAPPED structure. That way you can retrieve the actual status later, when the connection attempt finishes.