从 ping 主机 c# 捕获 IpAddress

Catch the IpAddress from ping host c#

我想问一下是否可以从ping主机获取IpAddress。因此,如果有人对我的计算机执行 ping 操作,我就知道他的 IP 地址。我的代码如下所示:

        while (true)
        {
            Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
            icmpListener.Bind(new IPEndPoint(IPAddress.Parse("564.89.556.5"), 0));
            icmpListener.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 });
            byte[] buffer = new byte[4096];
            EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
            int bytesRead = icmpListener.ReceiveFrom(buffer, ref remoteEndPoint);
            string text = "ICMPListener received " + bytesRead + " from " + remoteEndPoint;
            Console.WriteLine(text);                
        }

在代码 运行 之后,有人 ping 我,我知道 ip 是 pingd,而不是来自 ping 主机的那个。感谢提供遮阳篷。

尝试:

var ip = icmpListener.RemoteEndPoint;

If you are using a connection-oriented protocol, the RemoteEndPoint property gets the EndPoint that contains the remote IP address and port number to which the Socket is connected. If you are using a connectionless protocol, RemoteEndPoint contains the default remote IP address and port number with which the Socket will communicate. You must cast this EndPoint to an IPEndPoint before retrieving any information. You can then call the IPEndPoint.Address method to retrieve the remote IPAddress, and the IPEndPoint.Port method to retrieve the remote port number.


当使用 cmd 来 ping 一台机器 (ping 127.0.0.1) 时,您正在使用 默认端口 80

ping 机器
Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
        icmpListener.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80));
        icmpListener.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 });
        while (true)
        {
            byte[] buffer = new byte[4096];
            EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
            int bytesRead = icmpListener.ReceiveFrom(buffer, ref remoteEndPoint);
            Console.WriteLine("ICMPListener received " + bytesRead + " from " + remoteEndPoint);
        }

在你做任何事情之前,以管理员身份打开CMD,然后键入以下命令:netsh advfirewall firewall add rule name="All ICMP v4" dir=in action=allow protocol=icmpv4:any,any 这将允许防火墙规则允许接收ICMP 端口无法访问的数据包。

并且不要忘记以管理员身份 运行 C# 程序