Last active
June 20, 2018 16:34
-
-
Save l3x/dfcc043bdc617bb0dd3fdce6146205ae to your computer and use it in GitHub Desktop.
GetIPv4Address - A Go function to get your host's IPv4 address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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