C#怎么定时判断网络IP地址和端口号是否能ping通
可以使用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结果打印到控制台上
原文地址: https://www.cveoy.top/t/topic/hdvL 著作权归作者所有。请勿转载和采集!