github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/catgo/cat-go/cat/utils.go (about) 1 package cat 2 3 import ( 4 "fmt" 5 "net" 6 "time" 7 ) 8 9 func getLocalhostIp() (ip net.IP, err error) { 10 ip = net.IPv4(127, 0, 0, 1) 11 12 addrs, err := net.InterfaceAddrs() 13 if err != nil { 14 return 15 } 16 17 for _, address := range addrs { 18 if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { 19 if ipnet.IP.To4() != nil { 20 ip = ipnet.IP 21 return 22 } 23 } 24 } 25 return 26 } 27 28 func ip2String(ip net.IP) string { 29 return fmt.Sprintf("%d.%d.%d.%d", ip[12], ip[13], ip[14], ip[15]) 30 } 31 32 func ip2HexString(ip net.IP) string { 33 return fmt.Sprintf("%02x%02x%02x%02x", ip[12], ip[13], ip[14], ip[15]) 34 } 35 36 func duration2Millis(duration time.Duration) int64 { 37 return duration.Nanoseconds() / time.Millisecond.Nanoseconds() 38 }