Go Raw UDP Socket on Windows — "An invalid argument was supplied" Error

151 views
Skip to first unread message

Kanak Bhatia

unread,
Mar 22, 2025, 6:12:19 AM3/22/25
to golang-nuts

Hey everyone,

I’m trying to learn how to build a raw UDP socket in Go (on Windows) using golang.org/x/sys/windows. My goal is to send and receive raw UDP packets.

What I’m trying to do:

1. Create a raw socket:


socket, err := windows.Socket(windows.AF_INET, windows.SOCK_RAW, windows.IPPROTO_IP) if err != nil { fmt.Printf("Error creating socket: %v\n", err) return } defer windows.Closesocket(socket)

2. Send a UDP message:

func sendUDPPacket(socket windows.Handle, srcPort, destPort int, targetIP string, data string) error {
payload := []byte(data)
packet := createUDPHeader(srcPort, destPort, payload)

// Define the target address (IP + Port)
addr := windows.SockaddrInet4{Port: destPort}
copy(addr.Addr[:], []byte{127, 0, 0, 1}) // Sending to localhost

// Send the packet
return windows.Sendto(socket, packet, 0, &addr)
}

3. Receive a UDP message:

func receiveUDPPacket(socket windows.Handle) {
buffer := make([]byte, 1024)

for {
// Receive data from the socket
n, from, err := windows.Recvfrom(socket, buffer, 0)
if err != nil {
fmt.Println("Error receiving data:", err)
break
}

// Extract the header (8 bytes) and payload
fmt.Printf("📩 Received raw packet (%d bytes): %x\n", n, buffer[:n])
fmt.Printf("👉 Payload: %s\n", buffer[8:n])
fmt.Printf("👉 From: %+v\n", from)
}
}

The problem:

Sending works perfectly, but receiving fails immediately with this error:

go run main.go 8000 8001 
🚀 Type your message (type 'exit' to quit): 
💬 Enter message: Error receiving data: An invalid argument was supplied. hello 
✅ Message sent! 
💬 Enter message: hello 2 
✅ Message sent!


I’m stuck and would love some help:

I’m still learning how raw sockets and protocols actually work. 

Jason E. Aten

unread,
Mar 22, 2025, 10:48:01 AM3/22/25
to golang-nuts
The Claude 3 Sonnet LLM gives this, which runs fine (I tested) on Windoze and the Go playground:

Jason E. Aten

unread,
Mar 22, 2025, 10:52:23 AM3/22/25
to golang-nuts
(I think raw sockets may require admin privs; at least Claude suggested this https://go.dev/play/p/ZdqkgiGyr-v )
Reply all
Reply to author
Forward
0 new messages