Go's net.Listener
interface looks like this:
type Listener interface {
// Accept waits for and returns the next connection to the listener.
Accept() (Conn, error)
// Close closes the listener.
// Any blocked Accept operations will be unblocked and return errors.
Close() error
// Addr returns the listener's network address.
Addr() Addr
}
But what is the Addr
actually used for? If I had to implement my own Listener that just returned an empty Addr().String()
but accepted and closed connections just fine, what implications would that have?
Some network protocols allow you to create a listener which listens on a random address. This is commonly used when you want to run multiple instances of your service at the same time, and thus you can't have them all listening on the same address. In these cases, the kernel will find one that's available, and put your listener there. But once you have a random address, you need to know what that address is so you can advertise it.
For example, with TCP & UDP, you can specify 0
as your port number:
package main
import (
"fmt"
"net"
)
func main() {
l, _ := net.Listen("tcp4", ":0")
fmt.Printf("Addr: %s
", l.Addr())
}
Results in something like:
Addr: 0.0.0.0:37733
To add to Patrick's answer, this particular method Addr()
to the interface type Listener
was added in Go1.0 in June 2009 in commit 5d2ee9d.
The reason at the time was:
add Addr() string to net.Listener interface.
use it to avoid use of fixed ports in tests.
That way the net/server_test.go
could listen on any available port, and still get back the exact address.
if network == "tcp" {
listenaddr += ":0"; // any available port
}
go runServe(t, network, listenaddr, listening, done);
addr := <-listening; // wait for server to start
With runServe()
returning the address through the channel, using the Addr()
method:
listening <- l.Addr();