You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PacketNet提取数据包的源/目的IP及端口信息?

如何用PacketNet仅提取并显示数据包的源IP、目的IP及两端端口

当前使用PacketNet库捕获数据包时,代码会输出全部详细信息,但我只想打印源IP地址、目的IP地址以及两端端口,能否将现有代码修改为只输出这些指定字段的形式?

原捕获代码:

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

可以实现需求,修改后的代码如下:

var device = CaptureDeviceList.Instance.FirstOrDefault(dev => dev.Description.Contains("Ethernet"));
var readTimeoutMilliseconds = 1000;
device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
device.Filter("not arp and host 192.168.0.10");

PacketCapture d;
var status = device.GetNextPacket(out d);
var rawCapture = d.GetPacket();
var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

// 提取IP层地址信息
var ipPacket = p.Extract<IpPacket>();
if (ipPacket != null)
{
    Console.WriteLine($"source = {ipPacket.SourceAddress}");
    Console.WriteLine($"destination = {ipPacket.DestinationAddress}");

    // 提取TCP端口
    var tcpPacket = ipPacket.Extract<TcpPacket>();
    if (tcpPacket != null)
    {
        Console.WriteLine($"source port = {tcpPacket.SourcePort}");
        Console.WriteLine($"destination port = {tcpPacket.DestinationPort}");
        return;
    }

    // 提取UDP端口
    var udpPacket = ipPacket.Extract<UdpPacket>();
    if (udpPacket != null)
    {
        Console.WriteLine($"source port = {udpPacket.SourcePort}");
        Console.WriteLine($"destination port = {udpPacket.DestinationPort}");
        return;
    }

    Console.WriteLine("该IP数据包不包含TCP/UDP端口信息");
}
else
{
    Console.WriteLine("捕获到的不是IP数据包");
}

关键说明:

  • Packet是所有数据包的基类,需通过Extract<T>()方法提取特定层的数据包(如IpPacket、TcpPacket)
  • 先判断IP包是否存在,再根据传输层类型(TCP/UDP)提取对应端口,避免空引用异常
  • 保留了原有的设备选择、过滤规则和捕获逻辑,仅修改了数据包解析后的输出部分

内容的提问来源于stack exchange,提问作者Sam1916

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:32:21