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

以下是一个示例代码:

using System;
using System.Net.NetworkInformation;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        string ipAddress = '192.168.0.1'; // 需要 ping 的 IP 地址
        int port = 80; // 需要 ping 的端口号

        while (true)
        {
            bool isPingable = PingIPAddress(ipAddress); // 判断 IP 地址是否 ping 通
            bool isPortOpen = CheckPort(ipAddress, port); // 判断端口是否开放

            Console.WriteLine($'{DateTime.Now} - IP:{ipAddress} {(isPingable ? '可达' : '不可达')},端口:{port} {(isPortOpen ? '开放' : '关闭')}');

            Thread.Sleep(5000); // 休眠 5 秒钟
        }
    }

    static bool PingIPAddress(string ipAddress)
    {
        Ping ping = new Ping();
        PingReply reply = ping.Send(ipAddress);

        return reply.Status == IPStatus.Success;
    }

    static bool CheckPort(string ipAddress, int port)
    {
        try
        {
            using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(ipAddress, port))
            {
                return true;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

上述代码中,使用 while 循环来定时执行 IP 地址和端口的 ping 操作,休眠时间为 5 秒钟。在 PingIPAddress 方法中,使用 Ping 类的 Send 方法来判断 IP 地址是否 ping 通;在 CheckPort 方法中,使用 TcpClient 类的构造函数来检查端口是否开放。最终,将 IP 地址和端口的 ping 结果打印到控制台上。

C# 定时判断网络 IP 地址和端口是否可达

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

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