c# - how to sniff packets in an app without relying on WinPCap?

前端 未结 2 1368

BACKGROUND: I now understand how to write a C# application that can monitor packets going in/out of the network card on the PC the application is running on. T

2条回答
  •  日久生厌
    2021-01-31 22:40

    Personally I would stick to WinPCap. But since you asked, it is possible to sniff packets from the network using for the following code to enable raw sockets.

    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
    s.Bind(new IPEndPoint(IPAddress.Parse(""), 0));
    s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
    byte[] inBytes = new byte[] { 1, 0, 0, 0 };
    byte[] outBytes = new byte[] { 0, 0, 0, 0 };
    s.IOControl(IOControlCode.ReceiveAll, inBytes, outBytes);
    

    Once this is done, you can use Socket.Receive or Socket.BeginReceive to read the raw IP packets.

提交回复
热议问题