0

我有一个 Golang 函数来解码 pcap 文件并获取应用层的有效负载。为此,我使用 gopacket。我的初始代码是:

func decodePcap(file string) ([][]byte, error) {
    var data [][]byte
    if handle, err := pcap.OpenOffline(file); err != nil {
        return nil, err
    } else {
        packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
        for packet := range packetSource.Packets() {
            d := packet.ApplicationLayer().Payload()
            data = append(data, d)
        }
   }
   return data, nil
}

此变通方法运行良好,但当 pacap 文件中存在碎片数据包时,此变通方法可能无法正常工作。为了解决这个问题,我在函数中添加了碎片整理:

func decodePcap(file string) ([][]byte, error) {
    var data [][]byte
    defragger := ip4defrag.NewIPv4Defragmenter()
    if handle, err := pcap.OpenOffline(file); err != nil {
        return nil, err
    } else {
        packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
        for packet := range packetSource.Packets() {
            in, err := defragger.DefragIPv4(packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
            if err != nil {
                continue
            } else if in == nil { //part of fragment continue
                continue
            }
            // How to get Application Layer Payload from *layers.IPv4
            // Now I remove 8 first bytes from IPv4 Payload, 
            // because I know there are UDP/IP packets in pcap file
            d := in.Payload[8:]
            data = append(data, d)
        }
   }
   return data, nil
}

我的问题是:如何使用 gopacket 从 layers.IPv4 获取应用层有效负载,而不是从 IPv4 有效负载中删除字节?

4

0 回答 0