How can I test a connection to a server with C# given the server's IP address?

前端 未结 4 1372
野的像风
野的像风 2020-12-30 04:15

How can I programmatically determine if I have access to a server with a given IP address using C#?

4条回答
  •  庸人自扰
    2020-12-30 05:10

    Declare string address and int port and you are ready to connect through the TcpClient class.

    System.Net.Sockets.TcpClient client = new TcpClient();
    try
    {
        client.Connect(address, port);
        Console.WriteLine("Connection open, host active");
    } catch (SocketException ex)
    {
        Console.WriteLine("Connection could not be established due to: \n" + ex.Message);
    }
    finally
    {
        client.Close();
    }
    

提交回复
热议问题