UDP packet capturing in c#

前端 未结 5 1074
灰色年华
灰色年华 2020-12-09 04:50

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
Desti         


        
5条回答
  •  醉梦人生
    2020-12-09 05:33

    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.

提交回复
热议问题