How to change the timeout of TcpClient.Connect?

Hong 1,246 Reputation points
2024-02-18T23:49:20.7866667+00:00
using (var client = new TcpClient())
{
    try
    {
        client.ReceiveTimeout = 1000;
        client.SendTimeout = 1000;
        client.Connect("1.2.3.4", 5); 
    }
    catch (SocketException)
    {
        Console.WriteLine("IP address is not reachable");
    }
}

Neither ReceiveTimeout nor SendTimeout makes any difference to the connection timeout. Is there way to modify the connection timeout? It takes 10 to 20 seconds for the connection to time out. It is too long.

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2024-02-19T03:42:50.32+00:00

    Hi @Hong ,

    You can use TcpClient.ConnectAsync Method to control the timeout period.

    if (!client.ConnectAsync("remotehost", remotePort).Wait(1000))
    {
        // connection failure
    }
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.