Connect method will block, unless you specifically set the Blocking property to false prior to calling Connect. If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. Connectionless protocols will not throw an exception because they simply establish a default remote host. You can use SocketException.ErrorCode to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error. If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. Use the Poll method to determine when the Socket is finished connecting.
But it is not the case with Mono..
Socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
Socket.Blocking = false;
Socket.Connect( "10.10.10.10", 123456 );
Socket.Connect should immediately throw a SocketConnection but nothing happens. After three minutes a SocketException is throwing...
System.Net.Sockets.SocketException: Connection timed out
at System.Net.Sockets.Socket.Connect (System.Net.IPAddress addresses, Int32 port) [0x00128] in /usr/src/packages/BUILD/mono-2.8.2/mcs/class/System/System.Net.Sockets/Socket.cs:1873
at System.Net.Sockets.Socket.Connect (System.String host, Int32 port) [0x00007] in /usr/src/packages/BUILD/mono-2.8.2/mcs/class/System/System.Net.Sockets/Socket.cs:1878
Same thing on all Mono Versions. 2.6.7, 2.8.2, 2.10.9, 3.1.2
Port 123456 will not working ever, sorry
I've noticed this recently in a project I have as well, and have figured out the root cause. This is still an issue in Mono 4.4. The root cause is that when a socket is set to non blocking, the Connect() method calls Poll() with a timeout of -1. This causes an infinite wait until the socket times out, which is not the proper behavior. The proper behavior works in .NET Core, as in .NET Core, if the socket is non blocking it returns the socket error immediately. The code in mono is labeled FIXME as well, so I have submitted a pull request to solve this issue. The pull request is located at https://github.com/mono/mono/pull/3368.