困惑于`telnet localhost`和`telnet 0.0.0.0`

时间:2018-04-30 08:28:47

标签: networking ip

我写了一个简单的GO程序,它听取0.0.0.0:9999127.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)
    }
}

代码的含义:

它绑定了两个地址,并对它们的客户端给出了不同的响应

  1. 绑定“0.0.0.0:9999”:将“111”重复发送给客户
  2. 绑定“127.0.0.1:9999”:将向客户端发送“222”重复
  3. 然后我使用telnet尝试不同的地址,响应是:

    • telnet 127.0.0.1 9999222(确定)
    • telnet localhost 9999111(为什么?!)
    • telnet 0.0.0.0 9999222(为什么?!)
    • telnet <my-internal-ip> 9999111(确定)

    我对其中一些人感到很困惑:

    • telnet localhost 9999111(为什么?!)

      localhost应指向127.0.0.1,因此我认为它与telnet 127.0.0.1 9999相同,响应应为222,但实际值为111 < / p>

    • telnet 0.0.0.0 9999222(为什么?!)

      我认为0.0.0.0127.0.0.1不一样,我希望得到111的回复,但得到222

    我还有一个演示项目:https://github.com/golang-demos/go-bind-0.0.0.0-127.0.0.1-demo

    更新:我的操作系统是OSX

1 个答案:

答案 0 :(得分:2)

操作系统将localhost0.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