1

In C# I'm trying to test connectivity to a port like this:

Socket socket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);

socket.Connect(telco.Address, telco.Port);

It works great when the port is available. However when the port is not available (e.g. google.com on TCP/81) it takes a long time (~60 seconds) for it to timeout. This is for a status page so I want to fail relatively quickly.

I tried to set socket.SendTimeout and socket.RecieveTimeout to 5000ms (5 seconds) but that appears to have no effect.

Steve Evans
  • 1,118
  • 2
  • 10
  • 16
  • You might need a workaround. See this similar question: http://stackoverflow.com/questions/1062035/how-to-config-socket-connect-timeout-in-c-sharp – Vlad Nov 04 '11 at 22:18

3 Answers3

1

I ended up going with code similar to this to maintain simplicity:

Socket socket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);

IAsyncResult result = socket.BeginConnect(telco.Address, telco.Port, null, null);

bool connectionSuccess = result.AsyncWaitHandle.WaitOne(5000, true);
Steve Evans
  • 1,118
  • 2
  • 10
  • 16
  • Don't run away from threads, as you'll soon or later bump into it since you are doing stuff asynchronously. – Daniel Mošmondor Nov 05 '11 at 11:48
  • This is for a status page, it checks a few TCP ports to see if they're alive and doesn't ever do anything with them. I think in this scenario running away from threads is the right thing to do. – Steve Evans Nov 07 '11 at 16:09
0

think you're looking for socket.ReceiveTimeout();

or use beginConnect() and use a sync tool such AutoResetEvent to catch the time out.

see this post: How to configure socket connect timeout

Community
  • 1
  • 1
MandoMando
  • 5,215
  • 4
  • 28
  • 35
0

To fine control your timeout, do this:

  • fire up one thread with the code above
  • after thread is fired and socket connection is attempted, do what you need (i.e. something you have a little time for, at least Application.DoEvents()
  • Thread.Sleep() for desired timeout interval. Or use some other method to make the time pass
  • check if the connection is open from your main thread. You can do this by observing some state variable that you'll set after successful connection is made.
  • if so, use the connection. If not, use Socket.Close() on your waiting socket to break the connection attempt.

Yes, you'll get the exception in the thread that tries to connect, but you can safely gobble it and assume that everything is OK.

http://msdn.microsoft.com/en-us/library/wahsac9k(v=VS.80).aspx Socket.Close()

Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99