可以使用System.Net.NetworkInformation命名空间中的Ping类来实现实时判断IP地址和端口号是否能ping通。

以下是一个简单的示例代码:

using System.Net.NetworkInformation;

public bool PingHost(string ipAddress, int port)
{
    Ping ping = new Ping();
    PingOptions options = new PingOptions();
    options.DontFragment = true;

    string data = "ping test data";
    byte[] buffer = Encoding.ASCII.GetBytes(data);
    int timeout = 1000;

    try
    {
        PingReply reply = ping.Send(ipAddress, timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect(ipAddress, port);
            tcpClient.Close();
            return true;
        }
    }
    catch (Exception)
    {
        // Ping或连接失败
    }

    return false;
}

这个方法首先使用Ping类进行ping测试,如果ping成功,则尝试连接指定的端口,如果连接成功,则返回true,否则返回false

C#怎么实现实时判断IP地址和端口号是否能ping通

原文地址: http://www.cveoy.top/t/topic/g1t5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录