使用os.Hostname()后,net.LookUpHost()不输出任何此类主机

I'm currently attempting to learn the programming language go and stubbled across this weird problem. I've created a simple go application that gets the Hostname succesfully, which I then try to get my addresses with. Finally I iterate over these addresses.

package main

import (
    "fmt"
    "net"
    "os"
    "strconv"
)

func main() {
    name, error := os.Hostname()
    fmt.Println("Name: " + name)
    fmt.Print("Error: ")
    fmt.Println(error)

    addrs, err := net.LookupHost(name)

    fmt.Println(addrs)

    fmt.Println(err)

    for indx, addr := range addrs {
        fmt.Println("Address number " + strconv.Itoa(indx) + ": " + addr)
    }
}

The output of this is the following:

Name: My-macbook.local
Error: <nil>
[]
lookup My-macbook.local: no such host

I also tried using net.LookUpIP(name), which resulted in the same. I'm connected to the internet and I checked that I had an ip address in system preferences -> network. I am currently on a Macbook Pro with macOS Sierra.

My friend ran the exact same code with the exact same version of go and had two addresses returned so do I have something preventing me from seeing my Ip addresses. Has anyone experienced this before?

The .local address you are trying to resolve is not a regular DNS entry, its a special one for local networks. It has several names such as bonjour, avahi etc. The RFC calls it mdns https://en.wikipedia.org/wiki/.local, see also dns service discovery.

According to the doc you should try to set this environment variable export GODEBUG=netdns=cgo in order to force the golang dns resolver to call for the system libraries. Indeed the pure golang DNS resolver does not resolve mdns.

You could also try an alternate mdns golang implementation such as https://github.com/hashicorp/mdns

Note also that the net package provides a DefaultResolver variable that you may override with a custom implementation to resolve \.local$.