Skip to content

Instantly share code, notes, and snippets.

@l3x
Last active June 20, 2018 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save l3x/dfcc043bdc617bb0dd3fdce6146205ae to your computer and use it in GitHub Desktop.
Save l3x/dfcc043bdc617bb0dd3fdce6146205ae to your computer and use it in GitHub Desktop.
GetIPv4Address - A Go function to get your host's IPv4 address
// GetIPv4Address returns this node's IPv4 IP Address
// If more than one IP address found, call GetPreferredOutboundIP
// 127.0.0.1 will be returned if no other IPv4 addresses are found;
// otherwise, the non 127.0.0.1 address will be returned
// Assumes node has at least one interface (and the 127.0.0.1 address)
// If any errors occur, 127.0.0.1 will be returned
func getIPv4Address() (net.IP, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
var ips []net.IP
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip != nil {
ips = append(ips, ip)
}
}
}
if len(ips) > 0 {
for _, ip := range ips {
if ip.To4() != nil && !ip.IsLoopback() {
return ip.To4(), nil
}
}
}
return getPreferredOutboundIP()
}
// getPreferredOutboundIP gets the preferred outbound ip address
func getPreferredOutboundIP() (net.IP, error) {
conn, err := net.Dial("udp", "9.9.9.9:9999")
if err != nil {
return nil, error
}
defer closeConn(conn)
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment