import ( "github.com/google/gopacket" "github.com/google/gopacket/layers" ) // Create an Ethernet packet with IPv4 payload eth := &layers.Ethernet{ SrcMAC: net.HardwareAddr{0x00, 0x11, 0x22, 0x33, 0x44, 0x55}, DstMAC: net.HardwareAddr{0x00, 0x66, 0x77, 0x88, 0x99, 0xaa}, EtherType: layers.EthernetTypeIPv4, } ip := &layers.IPv4{ SrcIP: net.IP{192, 0, 2, 1}, DstIP: net.IP{192, 0, 2, 2}, Protocol: layers.IPProtocolTCP, } // Create the packet builder and add the Ethernet and IPv4 layers pb := gopacket.NewPacketBuilder(layers.LinkTypeEthernet, eth, ip) // Build the packet packet := pb.Build()
import ( "github.com/google/gopacket" "github.com/google/gopacket/layers" ) // Create a TCP packet with SYN flag set eth := &layers.Ethernet{ SrcMAC: net.HardwareAddr{0x00, 0x11, 0x22, 0x33, 0x44, 0x55}, DstMAC: net.HardwareAddr{0x00, 0x66, 0x77, 0x88, 0x99, 0xaa}, EtherType: layers.EthernetTypeIPv4, } ip := &layers.IPv4{ SrcIP: net.IP{192, 0, 2, 1}, DstIP: net.IP{192, 0, 2, 2}, Protocol: layers.IPProtocolTCP, } tcp := &layers.TCP{ SrcPort: layers.TCPPort(1234), DstPort: layers.TCPPort(80), Seq: 1234567, Ack: 0, DataOffset: 5, Window: 1024, Flags: layers.TCPFlagSyn, } // Create the packet builder and add the Ethernet, IPv4, and TCP layers pb := gopacket.NewPacketBuilder(layers.LinkTypeEthernet, eth, ip, tcp) // Build the packet packet := pb.Build()In both examples, the `PacketBuilder` is used to construct a packet with multiple layers. The layers are passed as arguments to the `NewPacketBuilder` function, and the resulting packet is returned by the `Build` method. The examples demonstrate how to create packets with different types of layers, such as Ethernet, IPv4, and TCP, and how to set various fields in those layers.