amuz.es/src/infra/goutils@v0.1.3/net/local.go (about)

     1  package net
     2  
     3  import "net"
     4  
     5  // GetLocalIP returns the non loopback local IP of the host
     6  func GetLocalIP() 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  func ResolveIp(name string) (net.IP, error) {
    23  	if addrs, err := net.ResolveIPAddr("ip4", name); err != nil {
    24  		return nil, err
    25  	} else {
    26  		return addrs.IP, nil
    27  	}
    28  }
    29  
    30  func ExtractIp(remoteAddr net.Addr) string {
    31  	if addr, ok := remoteAddr.(*net.TCPAddr); ok {
    32  		return addr.IP.String()
    33  	} else {
    34  		return remoteAddr.String()
    35  	}
    36  }