infra
/
goutils
Archived
1
0
Fork 0
This repository has been archived on 2022-04-06. You can view files and clone it, but cannot push or open issues or pull requests.
goutils/net/local.go

37 lines
771 B
Go

package net
import "net"
// GetLocalIP returns the non loopback local IP of the host
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
func ResolveIp(name string) (net.IP, error) {
if addrs, err := net.ResolveIPAddr("ip4", name); err != nil {
return nil, err
} else {
return addrs.IP, nil
}
}
func ExtractIp(remoteAddr net.Addr) string {
if addr, ok := remoteAddr.(*net.TCPAddr); ok {
return addr.IP.String()
} else {
return remoteAddr.String()
}
}