Created
June 22, 2019 22:39
-
-
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"?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Linux:
Mac: