Manjoor
Manjoor

Reputation: 4199

UDP packet capturing in c#

Wireshark captures UDP packets in my LAN with follwoing details

Source IP            192.168.1.2
Destination IP      233.x.x.x
Source Port        24098
Destination Port      12074,12330

how can i capture it in c#?

Upvotes: 14

Views: 36923

Answers (5)

williambarau
williambarau

Reputation: 511

Using Pcap.Net in https://github.com/PcapDotNet

Especific exemple: https://github.com/PcapDotNet/Pcap.Net/wiki/Pcap.Net-Tutorial-Interpreting-the-packets

// Callback function invoked by libpcap for every incoming packet
    private static void PacketHandler(Packet packet)
    {
        // print timestamp and length of the packet
        Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);

        IpV4Datagram ip = packet.Ethernet.IpV4;
        UdpDatagram udp = ip.Udp;

        // print ip addresses and udp ports
        Console.WriteLine(ip.Source + ":" + udp.SourcePort+ " -> " + ip.Destination + ":" + udp.DestinationPort);
    }

Output: 2009-09-12 11:25:51.117 length:84 10.0.0.8:49003 -> 208.67.222.222:53 2009-09-12 11:25:51.212 length:125 208.67.222.222:53 -> 10.0.0.8:49003 2009-09-12 11:25:54.323 length:80 10.0.0.8:39209 -> 208.67.222.222:53 2009-09-12 11:25:54.426 length:75 10.0.0.8:47869 -> 208.67.222.222:53 2009-09-12 11:25:54.517 length:236 208.67.222.222:53 -> 10.0.0.8:39209 2009-09-12 11:25:54.621 length:91 208.67.222.222:53 -> 10.0.0.8:47869

Upvotes: 0

brickner
brickner

Reputation: 6585

In order to use WinPcap for raw packet capturing in C#, you can try Pcap.Net. It is a wrapper for WinPcap in C++/CLI and C# for easily capturing (sniffing) and injecting raw packets and it also contains an easy to use packets interpretation framework.

Upvotes: 1

Manjoor
Manjoor

Reputation: 4199

Solved it myself

Here is my working code

class CAA
{

    private Socket UDPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    private IPAddress Target_IP;
    private int Target_Port;
    public static int bPause;

    public CAA()
    {
        Target_IP = IPAddress.Parse("x.x.x.x");
        Target_Port = xxx;

        try
        {
            IPEndPoint LocalHostIPEnd = new
            IPEndPoint(IPAddress.Any, Target_Port);
            UDPSocket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
            UDPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            UDPSocket.Bind(LocalHostIPEnd);
            UDPSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
            UDPSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new
            MulticastOption(Target_IP));
            Console.WriteLine("Starting Recieve");
            Recieve();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message + " " + e.StackTrace);
        }
    }

    private void Recieve()
    {
        try
        {
            IPEndPoint LocalIPEndPoint = new
            IPEndPoint(IPAddress.Any, Target_Port);
            EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;
            StateObject state = new StateObject();
            state.workSocket = UDPSocket;
            Console.WriteLine("Begin Recieve");
            UDPSocket.BeginReceiveFrom(state.buffer, 0, state.BufferSize, 0, ref LocalEndPoint, new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void ReceiveCallback(IAsyncResult ar)
    {

            IPEndPoint LocalIPEndPoint = new
            IPEndPoint(IPAddress.Any, Target_Port);
            EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;
            int bytesRead = client.EndReceiveFrom(ar, ref LocalEndPoint);            



            client.BeginReceiveFrom(state.buffer, 0, state.BufferSize, 0, ref LocalEndPoint, new AsyncCallback(ReceiveCallback), state);
    }


    public static void Main()
    {       
        CAA o = new CAA();        
        Console.ReadLine();
    }

    public class StateObject
    {
        public int BufferSize = 512;
        public Socket workSocket;
        public byte[] buffer;

        public StateObject()
        {
            buffer = new byte[BufferSize];
        }
    }

}

Upvotes: 11

Matt Davis
Matt Davis

Reputation: 46034

Wireshark actually uses Winpcap to do this, and as the other answer indicates, you can use it as well.

You can also use the System.Net.Sockets.Socket class and place it in promiscuous mode. I use this to capture the IP traffic (e.g., TCP and UDP) from a given network interface. Here's an example.

using System.Net;
using System.Net.Sockets;

Socket socket =
    new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Bind(new IPEndPoint(IPAddress.Parse("X.X.X.X"), 0)); // specify IP address
socket.ReceiveBufferSize = 2 * 1024 * 1024; // 2 megabytes
socket.ReceiveTimeout = 500; // half a second
byte[] incoming = BitConverter.GetBytes(1);
byte[] outgoing = BitConverter.GetBytes(1);
socket.IOControl(IOControlCode.ReceiveAll, incoming, outgoing);

Now that the socket is created and configured, you can use the Receive() method to start receiving data. Each time you call Receive(), the returned buffer will contain an IP packet. See here for the breakout of the IPv4 header, here for the UDP header, and here for the TCP header. If the Protocol field of the IP header contains a value of 17, then you have a UDP packet.

NOTE Raw sockets on Windows require that you be an administrator on your local system. The following language is contained in this MSDN article.

To use a socket of type SOCK_RAW requires administrative privileges. Users running Winsock applications that use raw sockets must be a member of the Administrators group on the local computer, otherwise raw socket calls will fail with an error code of WSAEACCES. On Windows Vista and later, access for raw sockets is enforced at socket creation. In earlier versions of Windows, access for raw sockets is enforced during other socket operations.

Upvotes: 8

Chathuranga Chandrasekara
Chathuranga Chandrasekara

Reputation: 20906

The Winpcap library is one of the best ways to do this. I have experience in doing this in C# and it was really easy to work with this library.

This project shows how to do it with C#.

Upvotes: 8

Related Questions