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

前端 未结 4 1357
野的像风
野的像风 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 04:50

    This should do it

    bool ssl;
    ssl = false;
    int maxWaitMillisec;
    maxWaitMillisec = 20000;
    int port = 555;
    
    success = socket.Connect("Your ip address",port,ssl,maxWaitMillisec);
    
    
    if (success != true) {
    
        MessageBox.Show(socket.LastErrorText);
        return;
    }
    
    0 讨论(0)
  • 2020-12-30 04:59

    You could use the Ping class (.NET 2.0 and above)

        Ping x = new Ping();
        PingReply reply = x.Send(IPAddress.Parse("127.0.0.1"));
    
        if(reply.Status == IPStatus.Success)
            Console.WriteLine("Address is accessible");
    

    You might want to use the asynchronous methods in a production system to allow cancelling, etc.

    0 讨论(0)
  • 2020-12-30 05:06

    Assuming you mean through a TCP socket:

    IPAddress IP;
    if(IPAddress.TryParse("127.0.0.1",out IP)){
        Socket s = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream,
        ProtocolType.Tcp);
    
        try{   
            s.Connect(IPs[0], port);
        }
        catch(Exception ex){
            // something went wrong
        }
    }
    

    For more information: http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题