How do I get the local IP address in Go?

后端 未结 8 1389
花落未央
花落未央 2020-12-02 07:04

I want to get the computer\'s IP address. I used the code below, but it returns 127.0.0.1.

I want to get the IP address, such as 10.32.10.111

8条回答
  •  自闭症患者
    2020-12-02 07:30

    net.LookupHost() on your os.Hostname() is probably always going to give you 127.0.0.1, because that's what's in your /etc/hosts or equivalent.

    I think what you want to use is net.InterfaceAddrs():

    func InterfaceAddrs() ([]Addr, error)

    InterfaceAddrs returns a list of the system's network interface addresses.

提交回复
热议问题