查找某个端口上的传出连接的IP地址

时间:2012-12-14 16:22:25

标签: c# networking ip port

C#中是否有办法找到我在特定端口上连接的服务器的IP地址?

我知道端口总是28961,我想获得我在这个端口上连接的服务器的IP地址。

2 个答案:

答案 0 :(得分:3)

我写了一个类似的程序。我使用了SharpPcap装配体。下面的代码应该可以帮助您入门:

private void StartCapture(ICaptureDevice device)
    {
        // Register our handler function to the
        // 'packet arrival' event
        device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);

        // Open the device for capturing
        int readTimeoutMilliseconds = 1000;
        device.Open(DeviceMode.Normal, readTimeoutMilliseconds);

        device.Filter = "";

        // Start the capturing process
        device.StartCapture();
    }

private void device_OnPacketArrival(object sender, CaptureEventArgs e)
    {
        var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
        var ip = PacketDotNet.IpPacket.GetEncapsulated(packet);

        if (ip != null)
        {
            int destPort = 0;

            if (ip.Protocol.ToString() == "TCP")
            {
                var tcp = PacketDotNet.TcpPacket.GetEncapsulated(packet);

                if (tcp != null)
                {
                    destPort = tcp.DestinationPort;
                }
            }
            else if (ip.Protocol.ToString() == "UDP")
            {
                var udp = PacketDotNet.UdpPacket.GetEncapsulated(packet);

                if (udp != null)
                {
                    destPort = udp.DestinationPort;
                }
            }

            int dataLength = e.Packet.Data.Length;

            string sourceIp = ip.SourceAddress.ToString();
            string destIp = ip.DestinationAddress.ToString();

            string protocol = ip.Protocol.ToString();
        }
    }

通过实现自己的if语句,您应该能够通过使用上面的代码获得所需的内容。

答案 1 :(得分:0)

This CodeProject文章可能会对您有所帮助。它链接到一个完全工作的演示项目下载。它已经存在了很长时间,毫无疑问,在更高版本的.NET中有更简单的方法可以做到这一点。但它仍然有效,应该能满足你的需求。

获得活动TCP / IP连接列表后,您应该拥有在端口28961上选择一个并获取IP地址所需的一切。

相关问题