When we use http.ListenAndServe
, what is the difference between:
http.ListenAndServe("0.0.0.0:80", nil)
and
http.ListenAndServe(":80", nil)
? Wouldn't both versions listen on all interfaces on port 80
?
When we use http.ListenAndServe
, what is the difference between:
http.ListenAndServe("0.0.0.0:80", nil)
and
http.ListenAndServe(":80", nil)
? Wouldn't both versions listen on all interfaces on port 80
?
The http.ListenAndServe()
function eventually calls net.Listen()
. The documentation for net.Listen
states that it will bind to the network provided to it:
For TCP networks, if the host in the address parameter is empty or a literal unspecified IP address, Listen listens on all available unicast and anycast IP addresses of the local system. To only use IPv4, use network "tcp4".
However, looking at the source for http.ListenAndServe()
we can see that it specifies "tcp"
as the network and not "tcp4"
. Therefore the call in your example code should result in identical behavior, i.e. both calls should bind to all available interfaces. However, digging further down into the golang source we end up in internetAddrList()
and we can see that it differentiates between an empty host
value and one that has a ipv4 address specified. So golang does infact treat the ipv4 address specified as an indication to only bind on that interface.