NMunro
NMunro

Reputation: 1290

Find IP Address of Outgoing Connection on a Certain Port

Is there a way in C# to find the IP address of a server that I'm connecting to on a specific port?

I know the port will always be 28961, and I want to get the IP address of the server that I'm connecting to on this port.

Upvotes: 2

Views: 1463

Answers (2)

Carman Babin
Carman Babin

Reputation: 174

I have written a program that does something similar. I used the SharpPcap Assemblies. The code below should be able to get you started:

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();
        }
    }

by implementing your own if statements you should be able to get what you need by using the code above.

Upvotes: 3

Holf
Holf

Reputation: 6432

This CodeProject article may help you. It links to a fully working demo project download. It's been around for a long time and no doubt there are easier ways to do some of this in later versions of .NET. But it still works and should give you what you need.

Once you've got the list of active TCP/IP connections you should have everything you need to pick out the one on port 28961 and grab the IP address.

Upvotes: 0

Related Questions