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
?
"means that port 80 is listening to all interfaces (not used)" not exactly - the service "World Wide Web Publishing Service" was listening at this port. Once you manually stop it, you might free that port (at least in windows 7) – despot Jan 28 '13 at 12:45
The *:80 is used on the Virtual Host definition and not on the Listen directives in httpd.conf The * means listen on any ip address, and is simpler than specifying your actual IP Address. As most Windows PC's have only one IP address i.e. only one network card there is no need t be specific with the ip address. answered Mar 12 '16 at 14:08
Because 'Listen :80' does not exist in my file exactly as typed. – Orange WebDev Mar 12 '16 at 16:59 if it is not preset than yes you have to put this line in your configuration file. – Siddharth sharma Mar 12 '16 at 17:01 | Show 4more comments 2 Answers 2 ActiveOldestVotes 0
0.0.0.0, in this context, means "all IP addresses on the local machine" (in fact probably, "all IPv4 addresses on the local machine"). So, if your webserver machine has two IP addresses, 192.168.1.1 and 10.1.2.1, and you allow a webserver daemon like apache to listen on 0.0.0.0, it will be reachable at both of those IP addresses.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With