C#:检测目标服务器的IP 端口的通信性。(TCP and UDP)
address:远程主机的ip地址 port:远程主机需要检测的端口
TCP
try
{
IPHostEntry host = Dns.GetHostEntry(address);
IPAddress ip = host.AddressList[0];
IPEndPoint point = new IPEndPoint(ip, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(point);
Console.WriteLine("连接TCP端口{0}成功!", point);
}
catch (SocketException e)
{
Console.WriteLine("连接TCP端口{0}失败!", point);
}
UDP
try
{
var ntpData = new byte[48];
ntpData[0] = 11;
var addresses = Dns.GetHostEntry(address);
IPAddress ip = addresses.AddressList[0];
var ipEndPoint = new IPEndPoint(ip, port);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
Console.WriteLine("连接UDP端口{0}成功!", point);
}
catch
{
Console.WriteLine("连接UDP端口{0}失败!", point);
}
|