Skip to content

Instantly share code, notes, and snippets.

@zxh
Created February 9, 2018 07:43
Show Gist options
  • Save zxh/b3ff8d94578a0332f5b4e6b50a8398d7 to your computer and use it in GitHub Desktop.
Save zxh/b3ff8d94578a0332f5b4e6b50a8398d7 to your computer and use it in GitHub Desktop.
golang get ip address
func getIp() (net.IP, error) {
interfaces, e := net.Interfaces()
if e != nil {
return nil, errors.New("get Interfaces error")
}
for _, i := range interfaces {
// the flags value maybe 'pointtopoint', it also has a ip, filter it.
if !strings.Contains(i.Flags.String(), "broadcast") {
continue
}
addresses, e := i.Addrs()
if e != nil {
return nil, errors.New("get addresses failed")
}
for _, add := range addresses {
var ip net.IP
switch t := add.(type) {
case *net.IPNet:
ip = t.IP
case *net.IPAddr:
ip = t.IP
}
// filter loopback ip
if !ip.IsLoopback() && ip.To4() != nil {
// return the first occurrence ip
return ip, nil
}
}
}
return nil, errors.New("find none ip")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment