Go语言获取ip

作者: 吴佳浩 | 来源:发表于2021-01-19 10:23 被阅读0次

    获取本地内网ip

    import (
        "net"
    )
    
    // LocalIPs return all non-loopback IPv4 addresses
    func LocalIPv4s() ([]string, error) {
        var ips []string
        addrs, err := net.InterfaceAddrs()
        if err != nil {
            return ips, err
        }
    
        for _, a := range addrs {
            if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
                ips = append(ips, ipnet.IP.String())
            }
        }
    
        return ips, nil
    }
    
    // GetIPv4ByInterface return IPv4 address from a specific interface IPv4 addresses
    func GetIPv4ByInterface(name string) ([]string, error) {
        var ips []string
    
        iface, err := net.InterfaceByName(name)
        if err != nil {
            return nil, err
        }
    
        addrs, err := iface.Addrs()
        if err != nil {
            return nil, err
        }
    
        for _, a := range addrs {
            if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
                ips = append(ips, ipnet.IP.String())
            }
        }
    
        return ips, nil
    }
    

    获取本机外网ip

    package main
    import (
        "net"
        "fmt"
        "strings"
    )
    func main() {
        conn, err := net.Dial("udp", "google.com:80")
        if err != nil {
            fmt.Println(err.Error())
            return
        }
        defer conn.Close()
        fmt.Println(strings.Split(conn.LocalAddr().String(), ":")[0])
    }
    

    相关文章

      网友评论

        本文标题:Go语言获取ip

        本文链接:https://www.haomeiwen.com/subject/dcosbktx.html