Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set test TCP connection timeout?

I try to test TCP connection with the following code.

System.Threading.Thread t = new System.Threading.Thread(() =>
{      
    using (TcpClient client = new TcpClient())
    {
        client.Connect(ip, Convert.ToInt32(port));
    }
});
t.Start();

How to set time out if the IP or port is invalid?

like image 373
Prince OfThief Avatar asked Jan 03 '11 10:01

Prince OfThief


People also ask

How do you set a TCP timeout value?

Move to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters. From the Edit menu select New - DWORD value. Enter a name of InitialRtt and press Enter. Double click the new value and set to the number of milliseconds for the timeout, e.g. 5000 for 5 seconds (the old default was 3 seconds).

How do I increase TCP connection timeout?

Some time it is necessary to increase or decrease timeouts on TCP sockets. You can use /proc/sys/net/ipv4/tcp_keepalive_time to setup new value. The number of seconds a connection needs to be idle before TCP begins sending out keep-alive probes. Keep-alives are only sent when the SO_KEEPALIVE socket option is enabled.

Do TCP connections timeout?

The Idle Timeout setting in the TCP profile specifies the length of time that a connection is idle before the connection is eligible for deletion. If no traffic flow is detected within the idle session timeout, the BIG-IP system can delete the session. The default is 300 seconds.


2 Answers

There is no built in way to do this. I use the following code for many of our application. The code is by no means original but works out okay. Please note that you may have to add retries to this function... sometimes it returns false even when the server is up and running.

  private static bool _TryPing(string strIpAddress, int intPort, int nTimeoutMsec)
    {
        Socket socket = null;
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);


            IAsyncResult result = socket.BeginConnect(strIpAddress, intPort, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(nTimeoutMsec, true);

            return socket.Connected;
        }
        catch
        {
            return false;
        }
        finally
        {
            if (null != socket)
                socket.Close();
        }
    }
like image 76
Saibal Avatar answered Sep 22 '22 12:09

Saibal


There is no direct way to achieve it, but one way to do it can be to have a seperate method which would test the connection.

 static bool TestConnection(string ipAddress, int Port, TimeSpan waitTimeSpan)
        {
            using (TcpClient tcpClient = new TcpClient())
            {
                IAsyncResult result = tcpClient.BeginConnect(ipAddress, Port, null, null);
                WaitHandle timeoutHandler = result.AsyncWaitHandle;
                try
                {
                    if (!result.AsyncWaitHandle.WaitOne(waitTimeSpan, false))
                    {
                        tcpClient.Close();
                        return false;
                    }

                    tcpClient.EndConnect(result);
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    timeoutHandler.Close();
                }
                return true;
            }
        }

This method would use a WaitHandle that would wait for the specified time period to get the connection established, if it gets connected in time, it would close the connection and return true, else, it would timeout and return false.

like image 43
Danish Khan Avatar answered Sep 22 '22 12:09

Danish Khan