【问题标题】:Puzzled about the `telnet localhost` and `telnet 0.0.0.0`对 `telnet localhost` 和 `telnet 0.0.0.0` 感到困惑
【发布时间】:2018-05-08 00:08:38
【问题描述】:

我写了一个简单的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”重复

然后我用telnet尝试不同的地址,得到的响应是:

  • telnet 127.0.0.1 9999:222(好的)
  • telnet localhost 9999: 111(为什么?!)
  • telnet 0.0.0.0 9999: 222(为什么?!)
  • telnet <my-internal-ip> 9999:111(好的)

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

  • telnet localhost 9999:111(为什么?!)

    localhost应该指向127.0.0.1,所以我认为它与telnet 127.0.0.1 9999相同,响应应该是222,但实际是111

  • telnet 0.0.0.0 9999:222(为什么?!)

    我认为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

【问题讨论】:

  • 使用0.0.0.0应该监听网络上的所有地址
  • 输出是什么意思;你在期待什么;这个输出和那个有什么不同?
  • @EJP 谢谢,我更新了问题并添加了更多解释
  • 但不是我要求的。我们是否理解服务器应该响应客户端的远程地址?
  • @EJP 再次更新,希望现在清楚了。

标签: networking ip


【解决方案1】:

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

【讨论】:

  • 对于 mac,情况不同:PING 0.0.0.0 (0.0.0.0): 56 data bytes ping: sendto: No route to host
猜你喜欢
  • 2021-11-28
  • 1970-01-01
  • 2013-03-29
  • 2014-11-02
  • 1970-01-01
  • 2014-03-18
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多