我编写了一个简单的GO程序,它可以监听0.0.0.0:9999和127.0.0.1:9999
func main() {
go bind("0.0.0.0:9999", "111 ")
go func() {
time.Sleep(2 * time.Second)
bind("127.0.0.1:9999", "222 ")
}()
time.Sleep(time.Hour)
}
func bind(address string, content string) {
fmt.Println("-------------", address, "-----------------")
listener, err := net.Listen("tcp", address)
if err != nil {
panic(err)
return
}
fmt.Println(listener.Addr().String())
conn, _ := listener.Accept()
for {
_, err := conn.Write([]byte(content))
if err != nil {
panic(err)
}
time.Sleep(1 * time.Second)
}
}守则的含义:
它绑定两个地址,并对它们的客户端给出不同的响应。
然后我使用telnet尝试不同的地址,响应如下:
telnet 127.0.0.1 9999:222 (OK)telnet localhost 9999:111 (为什么?!)telnet 0.0.0.0 9999:222 (为什么?!)telnet <my-internal-ip> 9999:111 (OK)我对其中的一些很困惑:
telnet localhost 9999:111 (为什么?!)
localhost应该指向127.0.0.1,所以我认为telnet 127.0.0.1 9999和响应应该是222,但是实际的响应应该是111telnet 0.0.0.0 9999:222 (为什么?!)
我认为0.0.0.0和127.0.0.1不一样,我希望得到111的响应,但得到222我还有一个演示项目:https://github.com/golang-demos/go-bind-0.0.0.0-127.0.0.1-demo
更新:我的操作系统是OSX
发布于 2018-04-30 20:32:19
操作系统将localhost和0.0.0.0解析为127.0.0.1。
$ ping 0.0.0.0
PING 0.0.0.0 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.024 ms$ping localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.035 ms`localhost可以根据/etc/hosts文件解决其他问题。
对Linux ping 0.0.0.0行为的一个很好的解释是here。
https://stackoverflow.com/questions/50096683
复制相似问题