Search code examples
c#.nettcpclient

"SocketException: No such host is known" when connecting to a port on local host


I am aware that there are already several questions on StackOverflow asking about this specific exception, but I haven't found an answer that resolves my issue.

Here is the relevant code snippet:

public static class Server
{
    public const string LocalHost = "http://127.0.0.1";
    public const int Port = 31311;
    public static readonly string FullAddress = $"{LocalHost}:{Port}";

    private static readonly TimeSpan RetryConnectionInterval = TimeSpan.FromSeconds(10);

    public static async Task AwaitStart()
    {
        try
        {
            TcpClient tcpClient = new TcpClient();
            ConnectionState connectionState = new ConnectionState(tcpClient);

            tcpClient.BeginConnect(
                host: HostAddress, 
                port: Port,
                requestCallback: PingCallback,
                state: connectionState);

            bool startedSuccessfully = connectionState.IsSuccess;

            while (!startedSuccessfully)
            {
                await Task.Delay(RetryConnectionInterval);
                startedSuccessfully = connectionState.IsSuccess;
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
        }
    }

    private static void PingCallback(IAsyncResult result)
    {
        ConnectionState state = (ConnectionState)result.AsyncState;

        try
        {
            state.TcpClient.EndConnect(result);
            state.IsSuccess = true;
            Console.WriteLine("The server is successfully started.");
        }
        catch (SocketException)
        {
            Console.WriteLine($"The server is not yet started. Re-attempting connection in {RetryConnectionInterval.Seconds} seconds.");

            Wait(RetryConnectionInterval).GetAwaiter().GetResult();
            state.TcpClient.BeginConnect(host: HostAddress, port: Port, requestCallback: PingCallback, state: state);
        }
    }

    private static async Task Wait(TimeSpan duration)
    {
        await Task.Delay(duration);
    }
}

public class ConnectionState
{
    public bool IsSuccess;
    public readonly TcpClient TcpClient;

    public ConnectionState(TcpClient tcpClient)
    {
        this.TcpClient = tcpClient;
    }
}

The exception is caught inside the catch clause in PingCallback(IAsyncResult result), with the error message "No such host is known".

When I run netstat -an, I can see that my local server is indeed listening on Port 31311:

enter image description here

If I change TcpClient tcpClient = new TcpClient(); to TcpClient tcpClient = new TcpClient(LocalHost, Port);, the same exception (with the same error message) is thrown there instead.

How can I fix this issue?


Solution

  • The host name is incorrectly specified. You should have the call something like below, when you are trying it without async.

    TcpClient tcpClient = new TcpClient("127.0.0.1", 31311);
    

    in the async connection, you should specify as below

    tcpClient.BeginConnect(host: "127.0.0.1", ...)
    

    This should fix it