conn, err := net.ListenPacket("udp", "127.0.0.1:1234") if err != nil { // handle error } defer conn.Close() data := []byte("Hello, world!") addr := &net.UDPAddr{ IP: net.ParseIP("127.0.0.1"), Port: 5678, } _, err = conn.WriteTo(data, addr) if err != nil { // handle error }
conn, err := net.ListenPacket("ip:icmp", "0.0.0.0") if err != nil { // handle error } defer conn.Close() data := []byte{0x45, 0x00, 0x00, 0x28, 0x12, 0x34, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0xc0, 0xa8, 0x01, 0x01, 0xc0, 0xa8, 0x01, 0x02, 0x08, 0x00, 0x7d, 0x17, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x61, 0x62, 0x63} addr := &net.IPAddr{ IP: net.ParseIP("192.168.1.2"), } _, err = conn.WriteTo(data, addr) if err != nil { // handle error }In this example, we create a `PacketConn` object listening on the ICMP protocol. We then create a raw IP packet in byte format and a destination IP address. We call the `WriteTo` method to send the packet to that address. The `WriteTo` method is part of the `net` package in Go.