我一直对使用SharpPcap非常感兴趣,但到目前为止进展并不顺利。
主要问题是以下代码:
private static void device_OnPacketArrival(object sender, CaptureEventArgs packet)
{
if(packet is TCPPacket)
{
DateTime time = packet.Timeval.Date;
int len = packet.PcapHeader.len;
TCPPacket tcp = (TCPPacket)packet;
string srcIp = tcp.SourceAddress;
string dstIp = tcp.DestinationAddress;
int srcPort = tcp.SourcePort;
int dstPort = tcp.DestinationPort;
Console.WriteLine("{0}:{1}:{2},
{3} Len={4} {5}:{6} -> {7}:{8}",
time.Hour, time.Minute, time.Second,
time.Millisecond, len, srcIp, srcPort,
dstIp, dstPort);
}
}
“找不到类型或命名空间 TCPPacket”
好的,所以我认为它一定是 TcpPacket?- 但后来出现了这个错误:
“给定的表达式永远不是提供的 ('PacketDotNet.TcpPacket') 类型”
忽略:
“‘SharpPcap.CaptureEventArgs’不包含‘Timeval’的定义,并且找不到接受‘SharpPcap.CaptureEventArgs’类型的第一个参数的扩展方法‘Timeval’”
等等等等。所以我的问题是,我错过了什么吗?
我有 PacketDotNet 和 SharpPcap 库,并添加了两个 using 语句。
解决方案: Packet pack = Packet.ParsePacket(packet.Packet); TcpPacket tcpPacket = TcpPacket.GetEncapsulated(pack);
DateTime time = packet.Packet.Timeval.Date;
int len = packet.Packet.Data.Length;
if (tcpPacket != null)
{
IpPacket ipPacket = (IpPacket)tcpPacket.ParentPacket;
IPAddress srcIp = ipPacket.SourceAddress;
IPAddress dstIp = ipPacket.DestinationAddress;
ushort srcPort = tcpPacket.SourcePort;
ushort dstPort = tcpPacket.DestinationPort;
MessageBox.Show(String.Format("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}",
time.Hour, time.Minute, time.Second, time.Millisecond, len,
srcIp, srcPort, dstIp, dstPort)
);
}