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. 

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/779656bb-7ad3-444e-b317-8999ed16ce29n%40googlegroups.com.

Reply via email to