dop83362 2018-04-16 03:26
浏览 49
已采纳

为什么http.Get(“ http:// [::]:1234”)有效?

I was writing a test where I wanted an HTTP server to listen on a random port and then connect to this port. I wrote:

mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Println("foo")
})

listener, err := net.Listen("tcp", ":0")
fmt.Println(err)

httpServer := &http.Server{Handler: mux}
go httpServer.Serve(listener)

fmt.Println("http://" + listener.Addr().String())  

r, err := http.Get("http://" + listener.Addr().String())
fmt.Println(r)
fmt.Println(err)

I meant to write net.Listen("tcp", "127.0.0.1:0") but accidentally wrote net.Listen("tcp", ":0").

For "http://" + listener.Addr().String() it prints:

http://[::]:1709

where as far as I understand the "bracket colon colon bracket" means "all interfaces".

To my surprise, the http.Get("http://[::]:1709") works, it connects to the webserver and "foo" is printed.

How is "http://[::]:1709" a valid address?

  • 写回答

1条回答 默认 最新

  • douzi8548 2018-04-16 05:04
    关注

    At least on a Linux system, this results in a connection being made to localhost.

    The address :: is IN6ADDR_ANY, typically used when listening to listen for connections to any IPv6 address on the system. It's analogous to INADDR_ANY, also known as 0.0.0.0 in IPv4.

    Occasionally someone attempts to use one of these addresses as the destination address for an outgoing connection. When this happens:

    When making an outgoing connection to 0.0.0.0, Linux actually connects from 127.0.0.1 to 127.0.0.1.

    Similarly, when making an outgoing connection to ::, Linux actually connects from ::1 to ::1. Here is an example, taken from one of my websites (which happens to be an IP address lookup tool):

    [error@murloc ~]$ curl -k -H "Host: myip.addr.space" https://[::]:8443/
    ::1
    

    For completeness, here is the IPv4 version:

    [error@murloc ~]$ curl -k -H "Host: myip.addr.space" https://0.0.0.0:8443/
    127.0.0.1
    

    Note that this is OS-specific. You would have received an error on Windows.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)