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 [email protected].
To view this discussion visit
https://groups.google.com/d/msgid/golang-nuts/779656bb-7ad3-444e-b317-8999ed16ce29n%40googlegroups.com.