Is there any way to show the packet's dst ip address, src ip address and both port only?
var device = CaptureDeviceList.Instance.FirstOrDefault(dev => dev.Description.Contains("Ethernet"));//set capture interface to ethernet.
var defaultOutputType = StringOutputType.VerboseColored;//show the details of packet
var readTimeoutMilliseconds = 1000;
device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
device.Filter("not arp and host 192.168.0.10");//set filter to capture ip-packets only
PacketCapture d;
var status = device.GetNextPacket(out d);
var rawCapture = d.GetPacket();
var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
Console.WriteLine(p.ToString(defaultOutputType));//It will show all the details but I just want to print source IP and destination IP and Port
Can it change to something like this?
var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
Console.WriteLine("source = " + p.srcIP);
Console.WriteLine("destination = " + p.dstIP);
Console.WriteLine("source port = " + p.srcPort);
Console.WriteLine("destination port = " + p.dstPort);
Reference: Go To->Examples->CapturingAndParsingPackets->Main.cs
You would first have to check whether the payload of the encapsulating packet (which might be an ethernet frame) is actually an ip-packet:
var p = Packet.ParsePacket(rawCapture.GetLinkLayers(), rawCapture.Data);
if (p.PayloadPacket is IPv4Packet ipPacket)
{
Console.WriteLine($"dst: {ipPacket.DestinationAddress} | src: {ipPacket.SourceAddress}");
}
Of course, you could also check for is IPPacket...
in case you want to track IPv6 packets as well.
Thanks to @johnmoarr, here's the code to print the port aswell:
var p = Packet.ParsePacket(rawCapture.GetLinkLayers(), rawCapture.Data);
if (p.PayloadPacket is IPv4Packet ipPacket)
{
Console.WriteLine($"dst: {ipPacket.DestinationAddress} | src: {ipPacket.SourceAddress}");
if (ipPacket.PayloadPacket is TcpPacket tcpPacket)
{
Console.WriteLine($"dst port: {tcpPacket.DestinationPort} | src port: {tcpPacket.SourcePort}");
}
else if (ipPacket.PayloadPacket is UdpPacket udpPacket)
{
code...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.