amuz.es/src/go/misc@v1.0.1/networking/local.go (about)

     1  package networking
     2  
     3  import "net"
     4  
     5  // LocalIP returns the non loopback local IP of the host
     6  func LocalIP() string {
     7  	addrs, err := net.InterfaceAddrs()
     8  	if err != nil {
     9  		return ""
    10  	}
    11  	for _, address := range addrs {
    12  		// check the address type and if it is not a loopback the display it
    13  		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
    14  			if ipnet.IP.To4() != nil {
    15  				return ipnet.IP.String()
    16  			}
    17  		}
    18  	}
    19  	return ""
    20  }
    21  
    22  // ResolveIp is resolve a network address from a given hostname with default resolver.
    23  func ResolveIp(name string) (net.IP, error) {
    24  	if addrs, err := net.ResolveIPAddr("ip4", name); err != nil {
    25  		return nil, err
    26  	} else {
    27  		return addrs.IP, nil
    28  	}
    29  }
    30  
    31  func ExtractIp(remoteAddr net.Addr) string {
    32  	if addr, ok := remoteAddr.(*net.TCPAddr); ok {
    33  		return addr.IP.String()
    34  	} else {
    35  		return remoteAddr.String()
    36  	}
    37  }