0

我想使用 gopacket 从原始字节创建一个数据包并将数据包写入 pcap 文件。

我从原始字节创建了一个 UDP 数据包,如下所示。

package main

import (
        "fmt"
        "net"
        "log"
        "os"
        "time"
        //"encoding/hex"
        "github.com/google/gopacket"
        "github.com/google/gopacket/layers"
        "github.com/google/gopacket/pcap"
        "github.com/google/gopacket/pcapgo"
)

var (
        device       string = "eth0"
        snapshot_len int32  = 65535
        promiscuous  bool   = false
        err          error
        timeout      time.Duration = 30 * time.Second
        handle       *pcap.Handle
        buffer       gopacket.SerializeBuffer
        options      gopacket.SerializeOptions
)

func main() {
        ethernetLayer := &layers.Ethernet{
            SrcMAC: net.HardwareAddr{0xFF, 0xAA, 0xFA, 0xAA, 0xFF, 0xAA},
            DstMAC: net.HardwareAddr{0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD},
        }
        ipLayer := &layers.IPv4{
            SrcIP: net.IP{127,0,0,1},
            DstIP: net.IP{8,8,8,8},
        }
        udpLayer := &layers.UDP{
            SrcPort: 51190,
            DstPort: 4789,
        }
        rawBytes := []byte{10, 20, 30}
        buffer = gopacket.NewSerializeBuffer()
        gopacket.SerializeLayers(buffer, options,
                ethernetLayer,
                ipLayer,
                udpLayer,
                gopacket.Payload(rawBytes),
        )
        outgoingPacket := buffer.Bytes()
        fmt.Println(outgoingPacket)
        ethpacket := gopacket.NewPacket(outgoingPacket,
                                    layers.LayerTypeEthernet,
                                    gopacket.Default )

我很惊讶如何将这些数据包写入 pcap 文件。这是代码的那一部分。

        f, err := os.Create("temp.pcap")
        if err != nil {
                log.Fatal(err)
                os.Exit(1)
        }
        defer f.Close()

        //handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
        //if err != nil {
        //        log.Fatal(err)
        //}
        //defer handle.Close()

        //handle.WritePacketData(outgoingPacket)
        w := pcapgo.NewWriter(f)
        w.WriteFileHeader(uint32(snapshot_len), layers.LinkTypeEthernet)
        w.WritePacket(ethpacket.Metadata().CaptureInfo, ethpacket.Data())
       

这是我得到的错误。请帮助如何进一步进行

[root@centos-sqa-blr01 gopacket]# go run create_pcap.go
#command-line-arguments
./create_pcap.go:75:26: packet.MetaData undefined (type gopacket.Packet 没有字段或方法 MetaData,但是有有元数据)

4

1 回答 1

0

注意错误信息:“元数据”不是“元数据”。

猜你需要修改:

-            w.WritePacket(packet.MetaData().CaptureInfo, ethpacket.Data())
+            w.WritePacket(packet.Metadata().CaptureInfo, ethpacket.Data())

更新:

如果您只想创建和编写一个数据包,请注释以下代码。这个对我有用。

    // handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
    // if err != nil {
    //  log.Fatal(err)
    // }
    // defer handle.Close()
于 2021-08-21T07:38:05.610 回答