Skip to content

[Discussion]: how to bind a random address and a random port

Xin.Zh edited this page Mar 6, 2020 · 1 revision

Question

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

// server code
srcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
conn, err = net.ListenUDP("udp", srcAddr)

Client code

// 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

expect

the conn.LocalAddr is a random addr: [::1]:44733

actual

the conn.localAddr is: 0.0.0.0:0

Method of fix

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)