-
Notifications
You must be signed in to change notification settings - Fork 189
[Discussion]: how to bind a random address and a random port
Xin.Zh edited this page Mar 6, 2020
·
1 revision
I found a strange problem during unit testing, The PR.
The strange thing is that I did unit test results in other system (go version1.13/darwin amd64/linux amd64) without fault, but fault in travis env. -,-!
When use the follow code to start UDP server's listener. The client can't be assigned a random addr.
// server code
srcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
conn, err = net.ListenUDP("udp", srcAddr)
// client code
localAddr = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
// c.addr is the server's srcAddr
peerAddr, _ = net.ResolveUDPAddr("udp", c.addr)
for {
if c.IsClosed() {
return nil
}
conn, err = net.DialUDP("udp", localAddr, peerAddr)
// the conn.LocalAddr is 0.0.0.0:0. Means no `LocalAddr` assigned
the conn.LocalAddr is a random addr: [::1]:44733
the conn.localAddr is: 0.0.0.0:0
Assign IP to the server and client can be assigned a addr.
// assign local ip
ip := net.ParseIP("127.0.0.1")
srcAddr := &net.UDPAddr{IP: ip, Port: 0}
conn, err = net.ListenUDP("udp", srcAddr)