I am experimenting with pcap.net and wanted to implement something that responds to pings as an exercise. The operating system already responds to them, but I am fine with generating duplicates. The first step is obviously to even know that a ping packet has arrived. I modified the example at https://pcapdotnet.codeplex.com/wikipage?title=Pcap.Net%20Tutorial%20-%20Opening%20an%20adapter%20and%20capturing%20the%20packets&referringTitle=Pcap.Net%20User%20Guide to use the following handler.
I clearly don't understand what is happening because none of the captured packets are even on the right subnet. Sending ping packets to the destination ip makes no difference, though using ping -i 0 massively increases the number of received packets (but they still don't have plausible IP addresses and don't appear to be echo-request packets).
What am I doing wrong please?
private static void PacketHandler(Packet packet)
{
IpV4Address dst = packet.IpV4.Destination, src = packet.IpV4.Source;
if (dst == null || src == null) return;
if (packet.IpV4.Icmp != null)
{
Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length+" "+src+" -> "+dst);
}
}
Apparently, what I had meant to write was the following. It reliably gets both incoming and outgoing icmp echo requests. I have no idea why I don't also see masses of TCP packets going past as I am rdesktop-ed into the computer running this. But it seems to work well enough for what I wanted to do.
private static void PacketHandler(Packet packet)
{
if (packet.DataLink.Kind != DataLinkKind.Ethernet) return;
EthernetDatagram ed = packet.Ethernet;
if (ed.EtherType != EthernetType.IpV4) return;
IpV4Datagram ipv4 = ed.IpV4;
if (ipv4.Protocol != IpV4Protocol.InternetControlMessageProtocol) return;
IcmpDatagram icmp = ipv4.Icmp;
IpV4Address dst = ipv4.Destination, src = ipv4.Source;
Console.WriteLine(" length:" + packet.Length + " " + src + " -> " + dst + " " + icmp);
}