github.com/jtzjtz/kit@v1.0.2/net/ip.go (about) 1 package net 2 3 import ( 4 "errors" 5 "net" 6 ) 7 8 //获取本机内网ip 9 func GetLocalIp() string { 10 addr, err := net.InterfaceAddrs() 11 if err != nil { 12 return "127.0.0.1" 13 } 14 for _, add := range addr { 15 if ipnet, ok := add.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { 16 if ipnet.IP.To4() != nil { 17 return ipnet.IP.String() 18 } 19 } 20 } 21 return "127.0.0.1" 22 } 23 24 //获取本地ip 25 26 func GetIntranetIp() (string, error) { 27 addrs, err := net.InterfaceAddrs() 28 29 if err != nil { 30 return "", err 31 } 32 33 for _, address := range addrs { 34 35 // 检查ip地址判断是否回环地址 36 if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { 37 if ipnet.IP.To4() != nil { 38 return ipnet.IP.String(), nil 39 } 40 41 } 42 } 43 44 return "", errors.New("ip empty") 45 }