在使用 http.ListenAndServe
时,以下两种方式有何不同:
http.ListenAndServe("0.0.0.0:80", nil)
andhttp.ListenAndServe(":80", nil)
? 那两个版本不都会在端口80
上监听所有接口吗?
在使用 http.ListenAndServe
时,以下两种方式有何不同:
http.ListenAndServe("0.0.0.0:80", nil)
andhttp.ListenAndServe(":80", nil)
? 那两个版本不都会在端口80
上监听所有接口吗?
http.ListenAndServe()
函数最终会调用net.Listen()
。 net.Listen
的文档说明它将绑定到提供给它的网络:
但是,查看对于TCP网络,如果地址参数中的主机为空或为未指定的字面IP地址,则Listen会侦听本地系统的所有可用单播和任播IP地址。要仅使用IPv4,请使用网络“tcp4”。
http.ListenAndServe()
的源代码,我们可以看到它将"tcp"
指定为网络,而不是"tcp4"
。因此,您示例代码中的调用应导致相同的行为,即两个调用都应绑定到所有可用接口。但是,进一步深入golang源代码,我们进入internetAddrList()
,我们可以看到它区分了空的host
值和具有指定ipv4地址的值。因此,golang实际上将指定的ipv4地址视为仅在该接口上绑定的指示。
"0.0.0.0:80"
只绑定在 IPv4 接口上? - Emil Lbindv6only
选项(在 SO 答案中描述在此处 https://serverfault.com/a/39561/78427),这并不明显。基本上,在大多数发行版中,`bindv6only` 的值为 0,因此如果创建一个用于监听 IPv6 的套接字,它也将监听 IPv4。 - Patryk0.0.0.0
是v4+v6双栈。 - iBug