go lang 获取本机ip

方法一

func GetIp() {
    addrs, _ := net.InterfaceAddrs()
    log.Println(addrs)

    for _, addr := range addrs {
        if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
            if ipnet.IP.To4() != nil {
                log.Println(ipnet.IP.String())
            }
        }
    }
}

但是这个方法有个问题,如果本机存在虚拟机、docker等虚拟网卡,这类的ipv4地址同样能获取到

改进下,使用方法二

func GetIpV3() (string, error) {
    addrs, _ := net.Interfaces()
    //log.Println(addrs)

    for _, addr := range addrs {
        if addr.Flags & net.FlagUp == 0 {
            continue
        }

        if addr.Flags & net.FlagLoopback == 1 {
            continue
        }

        if !strings.Contains(addr.Name, "eth") {
            continue
        }

        addr_list, _ := addr.Addrs()
        //log.Println(addr.Name)

        for _, address := range addr_list {
            if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
                if ipnet.IP.To4() != nil {
                    //log.Println(ipnet.IP.String())
                    return ipnet.IP.String(), nil
                }
            }
        }
    }

    return "", errors.New("valid ip not found")
}

对网卡进行过滤。

Leave a Reply

Your email address will not be published. Required fields are marked *