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
Best regards