C#SharpPCap读取数据包内容

时间:2013-05-14 15:50:33

标签: c# packet-capture sharppcap

我正在尝试阅读使用SharpPCap捕获的数据包的内容。 这是我的小代码

private void button4_Click(object sender, EventArgs e)
        {
            // Retrieve the device list
            var devices = LibPcapLiveDeviceList.Instance;

            // Extract a device from the list
            var device = devices[1];

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

            // Open the device for capturing
            int readTimeoutMilliseconds = 1000;
            if (device is AirPcapDevice)
            {
                // NOTE: AirPcap devices cannot disable local capture
                var airPcap = device as AirPcapDevice;
                airPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp, readTimeoutMilliseconds);
            }
            else if (device is WinPcapDevice)
            {
                var winPcap = device as WinPcapDevice;
                winPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp | SharpPcap.WinPcap.OpenFlags.NoCaptureLocal, readTimeoutMilliseconds);
            }
            else if (device is LibPcapLiveDevice)
            {
                var livePcapDevice = device as LibPcapLiveDevice;
                livePcapDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            }
            else
            {
                throw new System.InvalidOperationException("unknown device type of " + device.GetType().ToString());
            }

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            device.StartCapture();

            MessageBox.Show("-- Listening on {0}, hit 'Enter' to stop...",
                device.Description);

            // Stop the capturing process
            device.StopCapture();

            // Close the pcap device
            device.Close();

        }

private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            if (e.Packet.LinkLayerType == PacketDotNet.LinkLayers.Ethernet)
            {
                var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                var ethernetPacket = (PacketDotNet.EthernetPacket)packet;

                MessageBox.Show(System.Text.Encoding.ASCII.GetString(e.Packet.Data));
                packetIndex++;
            }
        }

我捕获了一个byte []数据包,但我不知道如何读取整个服务器响应。 谢谢你的帮助

0 个答案:

没有答案