我一直遵循http://www.codeproject.com/KB/IP/sharppcap.aspx上的指南,为我实现一个简单的数据包嗅探器以自动执行身份验证,我设法进入了“过滤”部分,到目前为止,必须对教程代码进行一些调整才能使其正常工作,但我现在为此感到难过。
我收到的错误是;
但是我还没有自己引用PacketDotNet(到目前为止,所有内容都是SharpPcap)。
到目前为止,我已经包含了整个代码,问题出在device_OnPacketArrival()函数中。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PacketDotNet;
using SharpPcap;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string ver = SharpPcap.Version.VersionString;
Console.WriteLine("SharpPcap {0}, Example1.IfList.cs", ver);
// Retrieve the device list
CaptureDeviceList devices = CaptureDeviceList.Instance;
// If no devices were found print an error
if (devices.Count < 1)
{
Console.WriteLine("No devices were found on this machine");
return;
}
// Extract a device from the list
ICaptureDevice device = devices[0];
// 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.Promiscuous, readTimeoutMilliseconds);
// tcpdump filter to capture only TCP/IP packets
string filter = "ip and tcp";
device.Filter = filter;
Console.WriteLine();
Console.WriteLine("-- The following tcpdump filter will be applied: \"{0}\"",
filter);
Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...",
device.Description);
// Start capturing packets indefinitely
device.Capture();
// Close the pcap device
// (Note: this line will never be called since
// we're capturing indefinitely
device.Close();
}
private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
var tcp = TcpPacket.GetEncapsulated(e.Packet);
}
}
}
最佳答案
SharpPcap.RawPacket用于保存通过网络适配器捕获的原始数据,但PacketDotNet需要在GetEncapsulated()方法起作用之前对数据包进行解析。您所需的步骤将如下所示:
var packet = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data);
然后,您可以通过将
TcpPacket
传递给GetEncapsulated()
方法来提取封装的packet
。SharpPcap源代码下载处的示例12(位于https://sourceforge.net/projects/sharppcap/中)显示了语法以及如何修改数据包。
请记住,
PacketType.GetEncapsulated()
返回对数据包那部分的引用,因此对其进行修改将更改原始数据包。关于c# - 无法从SharpPcap.RawCapture转换为PacketDotNet.P,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7379516/