aregm / nff-go

NFF-Go -Network Function Framework for GO (former YANFF)
BSD 3-Clause "New" or "Revised" License
1.38k stars 156 forks source link

Sending gopacket generated bytes #712

Open justmumu opened 4 years ago

justmumu commented 4 years ago

Hi,

First of all thank you for this amazing project. I am trying to use in my project. But i can't figure out how to generate packets with gopacket. Is this possible ?

I saw GeneratePacketFromByte function and I used with gopacket's bytes but I got error "wrong destination MAC address". I think somehow gopacket bytes is not suitable.

Example Code:

func generatePacketFromByte(emptyPacket *packet.Packet, context flow.UserContext) {
        srcMAC, _ := hex.DecodeString("xxx")
    dstMAC, _ := hex.DecodeString("xxx")

    eth := &layers.Ethernet{
        SrcMAC: net.HardwareAddr(srcMAC),
        DstMAC: net.HardwareAddr(dstMAC),
        EthernetType: layers.EthernetTypeIPv4,
    }
    ip := &layers.IPv4{
        Version: 4,
        IHL: 5,
        TTL: 64,
        Id: 0,
        Protocol: layers.IPProtocolUDP,
        SrcIP: net.ParseIP(SrcIP).To4(),
        DstIP: net.ParseIP(DstIP).To4(),
    }
    udp := &layers.UDP{
        SrcPort: layers.UDPPort(1234),
        DstPort: layers.UDPPort(1234),
    }
    udp.SetNetworkLayerForChecksum(ip)

        buf := gopacket.NewSerializeBuffer()
    opts := gopacket.SerializeOptions{
        FixLengths: true,
        ComputeChecksums: true,
    }
    err = gopacket.SerializeLayers(buf, opts, eth, ip, udp)
        if err != nil {
        panic(err)
    }

        packet.GeneratePacketFromByte(emptyPacket, buf.Bytes())
}
aregm commented 4 years ago

Hello @rasity ! You can use https://github.com/intel-go/nff-go/blob/master/examples/gopacketParserExample.go as a reference. You just need to specify the source and destination MAC addresses correctly. There are builtin types so you can do something like this:

DAddr:     types.MACAddress{0x00, 0x40, 0x05, 0x40, 0xef, 0x24},
SAddr:     types.MACAddress{0x00, 0x60, 0x08, 0x9f, 0xb1, 0xf3},