Skip to content

Instantly share code, notes, and snippets.

@omribahumi
Last active April 9, 2024 06:09
Show Gist options
  • Save omribahumi/5da8517497042152691e to your computer and use it in GitHub Desktop.
Save omribahumi/5da8517497042152691e to your computer and use it in GitHub Desktop.
IP_PKTINFO usage in Go
package main
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"syscall"
)
func main() {
serverAddr, _ := net.ResolveUDPAddr("udp", ":1025")
sConn, _ := net.ListenUDP("udp", serverAddr)
file, _ := sConn.File()
syscall.SetsockoptInt(int(file.Fd()), syscall.IPPROTO_IP, syscall.IP_PKTINFO, 1)
data := make([]byte, 1024)
oob := make([]byte, 1024)
bytes_read, oob_bytes_read, _, _, _ := sConn.ReadMsgUDP(data, oob)
fmt.Println(data[:bytes_read], oob[:oob_bytes_read])
oob_buffer := bytes.NewBuffer(oob)
msg := syscall.Cmsghdr{}
binary.Read(oob_buffer, binary.LittleEndian, &msg)
fmt.Println(msg)
if msg.Level == syscall.IPPROTO_IP && msg.Type == syscall.IP_PKTINFO {
packet_info := syscall.Inet4Pktinfo{}
binary.Read(oob_buffer, binary.LittleEndian, &packet_info)
fmt.Println(packet_info)
}
}
@omribahumi
Copy link
Author

For anyone running into this gist, the OSX (Darwin) implementation is broken because of a bug.
See https://code.google.com/p/go/issues/detail?id=8329&thanks=8329&ts=1404510948

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment