当我们使用 http.ListenAndServe
, 之间有什么区别:
http.ListenAndServe("0.0.0.0:80", nil)
和
http.ListenAndServe(":80", nil)
?难道两个版本都不会监听端口 80
上的所有接口(interface)吗?
最佳答案
http.ListenAndServe()
函数最终调用 net.Listen()
. net.Listen
的文档声明它将绑定(bind)到提供给它的网络:
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".
但是,查看 http.ListenAndServe()
的来源我们可以看到它指定 "tcp"
作为网络而不是 "tcp4"
。因此,您的示例代码中的调用应该导致相同的行为,即两个调用都应该绑定(bind)到所有可用接口(interface)。然而,进一步深入研究 golang 源代码,我们最终得到 internetAddrList()
。我们可以看到它区分了空 host
值和指定了 ipv4 地址的值。所以 golang 实际上将指定的 ipv4 地址视为仅绑定(bind)到该接口(interface)的指示。
关于http - 监听 "0.0.0.0:80"和 ":80"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49067160/