github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/util/ip.go (about) 1 package util 2 3 import ( 4 "net" 5 "strconv" 6 "strings" 7 ) 8 9 func GetLocalIp() (string, *Err) { 10 addrs, err := net.InterfaceAddrs() 11 if err != nil { 12 return "", WrapErr(EcAddrErr, err) 13 } 14 for _, a := range addrs { 15 if n, ok := a.(*net.IPNet); ok && 16 !n.IP.IsLoopback() && 17 n.IP.To4() != nil { 18 return n.IP.String(), nil 19 } 20 } 21 return "", WrapErr(EcAddrErr, err) 22 } 23 24 func IsLocalIp(ip string) bool { 25 addrs, err := net.InterfaceAddrs() 26 if err != nil { 27 return false 28 } 29 for _, a := range addrs { 30 if n, ok := a.(*net.IPNet); ok && 31 !n.IP.IsLoopback() && 32 n.IP.To4() != nil && 33 n.IP.String() == ip { 34 return true 35 } 36 } 37 return false 38 } 39 40 func CheckLocalIp(ip string) (string, *Err) { 41 if ip == "" { 42 return GetLocalIp() 43 } 44 if IsLocalIp(ip) { 45 return ip, nil 46 } 47 return "", NewErr(EcAddrErr, M{ 48 "error": "not local ip", 49 }) 50 } 51 52 func ParseAddrPort(addr string) (int, *Err) { 53 idx := strings.LastIndex(addr, ":") 54 if idx < 0 { 55 return 0, NewErr(EcParamsErr, M{ 56 "addr": addr, 57 }) 58 } 59 port, e := strconv.Atoi(addr[idx+1:]) 60 if e != nil { 61 return 0, NewErr(EcParamsErr, M{ 62 "addr": addr, 63 "error": e, 64 }) 65 } 66 return port, nil 67 }