Last active
April 9, 2024 06:09
-
-
Save omribahumi/5da8517497042152691e to your computer and use it in GitHub Desktop.
IP_PKTINFO usage in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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