Skip to content

Instantly share code, notes, and snippets.

@enobufs
Created June 22, 2019 22:39
Show Gist options
  • Save enobufs/0651a5b4bb6ab0081acc50b6bdae9f57 to your computer and use it in GitHub Desktop.
Save enobufs/0651a5b4bb6ab0081acc50b6bdae9f57 to your computer and use it in GitHub Desktop.
What happens if I send a UDP packet to "0.0.0.0"?
package main
import (
"fmt"
"net"
"time"
)
// Add an alias 127.0.0.2 to your lo0 with the following command (macOS) first:
// macOS
// $ sudo ifconfig lo0 alias 127.0.0.2 up
// linux
// $ sudo ifconfig lo add 127.0.0.2 up
func listen(address string) (net.PacketConn, chan struct{}, error) {
conn, err := net.ListenPacket("udp4", address)
if err != nil {
return nil, nil, err
}
fmt.Printf("listening on %s\n", conn.LocalAddr().String())
closeCh := make(chan struct{})
go func() {
for {
buf := make([]byte, 1500)
n, from, err := conn.ReadFrom(buf)
if err != nil {
close(closeCh)
break
}
fmt.Printf("%s received %d bytes from %s\n", address, n, from.String())
}
}()
return conn, closeCh, nil
}
func main() {
conn2, closeCh2, err := listen("127.0.0.2:1234")
if err != nil {
panic(err)
}
conn1, closeCh1, err := listen("127.0.0.1:1234")
if err != nil {
panic(err)
}
conn3, closeCh3, err := listen("0.0.0.0:0")
if err != nil {
panic(err)
}
toAddr := &net.UDPAddr{
IP: net.ParseIP("0.0.0.0"),
//IP: net.ParseIP("127.0.0.2"),
Port: 1234,
}
for i := 0; i < 10; i++ {
n, err := conn3.WriteTo([]byte("Hello"), toAddr)
if err != nil {
panic(err)
}
fmt.Printf(">>> sent %d bytes to %s\n", n, toAddr.String())
time.Sleep(50 * time.Millisecond)
}
time.Sleep(1 * time.Second)
conn1.Close()
conn2.Close()
conn3.Close()
<-closeCh1
<-closeCh2
<-closeCh3
fmt.Println("Done")
}
@enobufs
Copy link
Author

enobufs commented Jun 22, 2019

Linux:

  • Packet sent to 0.0.0.0:1234 is always received by listener on 127.0.0.1:1234
  • If remove the listener on 127.0.0.1:1234, the packet sent to 0.0.0.0:1234 is received by listener on 127.0.0.2:1234

Mac:

  • Packet sent to 0.0.0.0:1234 is only received by listener on 127.0.0.1:1234
  • Even the listener on 127.0.0.1:1234 is removed, the packet sent to 0.0.0.0:1234 is NOT received by listener on 127.0.0.2:1234

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment