Help With UDP Broadcast

Hello,

I am trying to communicate with another computer directly connected with an ethernet cable via UDP broadcast.

Here is server code:

package main

import (
	"fmt"
	"net"
)

func main() {
	//local address
	la, err := net.ResolveUDPAddr("udp4", "0.0.0.0:8000")
	if err != nil {
		fmt.Println(err)
		return
	}

	//listen
	c, err := net.ListenUDP("udp4", la)
	if err != nil {
		fmt.Println(err)
		return
	}

	//read
	bs := make([]byte, 4096)
	n, ra, err := c.ReadFromUDP(bs)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(n, ra)
}

Here is client code:

package main

import (
	"fmt"
	"net"
)

func main() {
	//local address
	la, err := net.ResolveUDPAddr("udp4", "1.2.3.4:8000")
	if err != nil {
		fmt.Println(err)
		return
	}

	ra, err := net.ResolveUDPAddr("udp4", "255.255.255.255:8000")
	if err != nil {
		fmt.Println(err)
		return
	}

	//dial
	c, err := net.DialUDP("udp4", la, ra)
	if err != nil {
		fmt.Println(err)
		return
	}

	//write
	n, err := c.Write([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%d bytes written\n", n)
}

Case 1: if these pcs have same gateway address there is no problem.
Case 2: if thse pcs are in same network sub group like 1.2.3.4 and 1.2.3.5 there is no problem.
Case 3: if these pcs have random ip addresses like 1.2.3.4 and 4.3.2.1 i can’t communicate.

I also checked all network interfaces have net.Flagbroadcast flag.

I am planning to use this communication to find another pc’s ip address which will have a random static ip address and which will be connected to my pc directly with an ethernet cable. Many devices has this “find device” feature.

UDP broadcast approach is correct ?

Need help :slight_smile:

Best regards

UDP broadcasts will work if the routing is correct
UDP broadcasts from a random address connected to a network that doesn’t route that address will not work
You probably want to use something like ARP instead

Thank you,

I solved my problem using raw ethernet frames.

Best regards

Sounds cool, would you mind share the minimal test cases that use the raw ethernet frames?

Sure, I can reference following article by Matt Lahyer. I used his libraries for raw ethernet frames.

https://mdlayher.com/blog/network-protocol-breakdown-ethernet-and-go/


1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.