gitee.com/gricks/utils@v1.0.8/ip.go (about) 1 package utils 2 3 import ( 4 "errors" 5 "net" 6 ) 7 8 // InterfaceIP return ip address by interface name. eg. eth0; 9 // 10 // Using net.Listen("tcp", "127.0.0.1:0") to got a random listen port 11 func InterfaceIP(face string) (string, error) { 12 ifs, err := net.InterfaceByName(face) 13 if err != nil { 14 return "", err 15 } 16 addrs, err := ifs.Addrs() 17 if err != nil { 18 return "", err 19 } 20 for _, addr := range addrs { 21 if ipnet, ok := addr.(*net.IPNet); ok { 22 if ipnet.IP.To4() != nil { 23 return ipnet.IP.String(), nil 24 } 25 } 26 } 27 return "", errors.New("unknow interface") 28 } 29 30 // InternalIP get internal ip. 31 func InternalIP() (string, error) { 32 return getInterfaceIP(true) 33 } 34 35 // InternalIP get internal ip. 36 func ExternalIP() (string, error) { 37 return getInterfaceIP(false) 38 } 39 40 func getInterfaceIP(internal bool) (string, error) { 41 inters, err := net.Interfaces() 42 if err != nil { 43 return "", err 44 } 45 for _, inter := range inters { 46 if !isUp(inter.Flags) { 47 continue 48 } 49 addrs, err := inter.Addrs() 50 if err != nil { 51 continue 52 } 53 for _, addr := range addrs { 54 if ipnet, ok := addr.(*net.IPNet); ok { 55 if ip4 := ipnet.IP.To4(); ip4 != nil { 56 if isInternalIP(ip4) == internal { 57 return ip4.String(), nil 58 } 59 } 60 } 61 } 62 } 63 return "", errors.New("not found") 64 } 65 66 // isUp Interface is up 67 func isUp(v net.Flags) bool { 68 return v&net.FlagUp == net.FlagUp 69 } 70 71 func isInternalIP(ip net.IP) bool { 72 return (ip[0] == 10) || 73 (ip[0] == 172 && ip[1] >= 16 && ip[1] <= 31) || 74 (ip[0] == 192 && ip[1] == 168) 75 }