How do I get the local IP address in Go?

huangapple go评论89阅读模式
英文:

How do I get the local IP address in Go?

问题

我想获取计算机的IP地址。我使用了下面的代码,但它返回的是127.0.0.1

我想获取IP地址,例如10.32.10.111,而不是回环地址。

name, err := os.Hostname()
if err != nil {
     fmt.Printf("Oops: %v\n", err)
     return
}

addrs, err := net.LookupHost(name)
if err != nil {
    fmt.Printf("Oops: %v\n", err)
    return
}

for _, a := range addrs {
    fmt.Println(a)
}
英文:

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, instead of the loopback address.

name, err := os.Hostname()
if err != nil {
     fmt.Printf("Oops: %v\n", err)
     return
}

addrs, err := net.LookupHost(name)
if err != nil {
    fmt.Printf("Oops: %v\n", err)
    return
}

for _, a := range addrs {
    fmt.Println(a)
}  

答案1

得分: 179

以下是获取首选出站 IP 地址的更好解决方案,当机器上存在多个 IP 接口时使用。

import (
    "log"
    "net"
    "strings"
)

// 获取本机的首选出站 IP
func GetOutboundIP() net.IP {
    conn, err := net.Dial("udp", "8.8.8.8:80")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    localAddr := conn.LocalAddr().(*net.UDPAddr)

    return localAddr.IP
}

这段代码通过使用 UDP 连接到 Google 的 DNS 服务器(8.8.8.8:80),然后获取本地地址来获取首选出站 IP 地址。

英文:

Here is a better solution to retrieve the preferred outbound ip address when there are multiple ip interfaces exist on the machine.

import (
    "log"
    "net"
    "strings"
)

// Get preferred outbound ip of this machine
func GetOutboundIP() net.IP {
    conn, err := net.Dial("udp", "8.8.8.8:80")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    localAddr := conn.LocalAddr().(*net.UDPAddr)

    return localAddr.IP
}

答案2

得分: 149

你需要遍历所有的网络接口。

ifaces, err := net.Interfaces()
// 处理错误
for _, i := range ifaces {
    addrs, err := i.Addrs()
    // 处理错误
    for _, addr := range addrs {
        var ip net.IP
        switch v := addr.(type) {
        case *net.IPNet:
            ip = v.IP
        case *net.IPAddr:
            ip = v.IP
        }
        // 处理 IP 地址
    }
}

Play(来自 util/helper.go)

英文:

You need to loop through all network interfaces

ifaces, err := net.Interfaces()
// handle err
for _, i := range ifaces {
    addrs, err := i.Addrs()
    // handle err
    for _, addr := range addrs {
        var ip net.IP
        switch v := addr.(type) {
        case *net.IPNet:
                ip = v.IP
        case *net.IPAddr:
                ip = v.IP
        }
        // process IP address
    }
}

Play (taken from util/helper.go)

答案3

得分: 45

为了确保获得非环回地址,只需在迭代时检查IP是否不是环回地址。

// GetLocalIP 返回主机的非环回本地IP
func GetLocalIP() string {
    addrs, err := net.InterfaceAddrs()
    if err != nil {
        return ""
    }
    for _, address := range addrs {
        // 检查地址类型,如果不是环回地址则显示
        if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
            if ipnet.IP.To4() != nil {
                return ipnet.IP.String()
            }
        }
    }
    return ""
}

以上是一个用于获取主机非环回本地IP的Go代码。

英文:

To ensure that you get a non-loopback address, simply check that an IP is not a loopback when you are iterating.

// GetLocalIP returns the non loopback local IP of the host
func GetLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}
	for _, address := range addrs {
		// check the address type and if it is not a loopback the display it
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

答案4

得分: 26

net.LookupHost()在你的os.Hostname()上可能总是会给你返回127.0.0.1,因为这是你的/etc/hosts或等效文件中的内容。

我认为你想要使用的是net.InterfaceAddrs()

func InterfaceAddrs() ([]Addr, error)

InterfaceAddrs返回系统的网络接口地址列表。

英文:

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.

答案5

得分: 16

这对我有用:

host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
for _, addr := range addrs {
    if ipv4 := addr.To4(); ipv4 != nil {
        fmt.Println("IPv4: ", ipv4)
    }   
}

与帖子中的示例不同,它仅返回非环回地址,例如10.120.X.X。

英文:

This worked for me:

host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
for _, addr := range addrs {
    if ipv4 := addr.To4(); ipv4 != nil {
        fmt.Println("IPv4: ", ipv4)
    }   
}

Unlike the poster's example, it returns only non-loopback addresses, e.g. 10.120.X.X.

答案6

得分: 4

func GetInternalIP() string {
itf, _ := net.InterfaceByName("enp1s0") //在这里填入你的接口
item, _ := itf.Addrs()
var ip net.IP
for _, addr := range item {
switch v := addr.(type) {
case *net.IPNet:
if !v.IP.IsLoopback() {
if v.IP.To4() != nil { //验证IP是否为IPv4
ip = v.IP
}
}
}
}
if ip != nil {
return ip.String()
} else {
return ""
}
}

英文:
func GetInternalIP() string {
	itf, _ := net.InterfaceByName("enp1s0") //here your interface
	item, _ := itf.Addrs()
	var ip net.IP
	for _, addr := range item {
		switch v := addr.(type) {
		case *net.IPNet:
			if !v.IP.IsLoopback() {
				if v.IP.To4() != nil {//Verify if IP is IPV4
					ip = v.IP
				}
			}
		}
	}
	if ip != nil {
		return ip.String()
	} else {
		return ""
	}
}

答案7

得分: 2

func resolveHostIp() (string) {

    netInterfaceAddresses, err := net.InterfaceAddrs()

    if err != nil { return "" }

    for _, netInterfaceAddress := range netInterfaceAddresses {
	
        networkIp, ok := netInterfaceAddress.(*net.IPNet)
	
        if ok && !networkIp.IP.IsLoopback() && networkIp.IP.To4() != nil {
		
            ip := networkIp.IP.String()

            fmt.Println("解析的主机IP: " + ip)

            return ip
        }
    }
    return ""
}

这是一个用于解析主机IP的Go语言函数。它通过获取网络接口地址列表,并遍历每个地址来找到非回环地址的IPv4地址。找到后,将其打印并返回。如果没有找到符合条件的地址,则返回空字符串。

英文:
func resolveHostIp() (string) {

    netInterfaceAddresses, err := net.InterfaceAddrs()

    if err != nil { return "" }

    for _, netInterfaceAddress := range netInterfaceAddresses {
	
	    networkIp, ok := netInterfaceAddress.(*net.IPNet)
	
	    if ok && !networkIp.IP.IsLoopback() && networkIp.IP.To4() != nil {
		
            ip := networkIp.IP.String()

		    fmt.Println("Resolved Host IP: " + ip)

		    return ip
	    }
    }
    return ""
}

答案8

得分: 0

如果你除了127.0.0.1之外只有一个IP地址,你可以在下面的代码中进行检查。

conn,err := net.Dial("ip:icmp","google.com")
fmt.Println(conn.LocalAddr())

第二个参数可以是除了127.0.0.1之外的任何IP地址。

英文:

If you only have one IP address except 127.0.0.1, You can check the code down here.

conn,err := net.Dial("ip:icmp","google.com")
fmt.Println(conn.LocalAddr())

The second parameter can be any IP address except 127.0.0.1

huangapple
  • 本文由 发表于 2014年5月9日 15:00:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/23558425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定