之前项目需要检测远端状态,起初尝试通过检测远端端口来实现,后方发现项目不适用改用其它方便,这里发出了给有需要的人。
原理:发送UDP报文到指定端口,如果该端口没有绑定UDP监听会反馈ICMP,有绑定则无返回。
实现流程,打开ICMP监听,给远端的端口发送UDP报文,如果收到ICMP反馈,说明该端口没有UDP监听,未收到反馈说明该端口有UDP检测(不考虑网络异常等特殊情况)。
代码附上
string _localIP = “192.1.3.125”;//本地IP
string _serverIP = “192.1.3.221”;//远端IP
main()
{
Thread thr = new Thread(IcmpListener);
thr.Start();//启动icmp监听
UdpCheck(5081); //发送udp包
}
private void UdpCheck( int port)
{
UdpClient udpclient = new UdpClient(11066);
udpclient.Connect(IPAddress.Parse(_serverIP), port);
udpclient.Send(new byte[2], 2); //向指定端口发udp包
}
public void IcmpListener()
{
while(true)
{
Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
icmpListener.Bind(new IPEndPoint(IPAddres