Skip to content

Instantly share code, notes, and snippets.

@rooty
Created October 13, 2014 22:15
Show Gist options
  • Save rooty/36cd9eb6941ae95974a4 to your computer and use it in GitHub Desktop.
Save rooty/36cd9eb6941ae95974a4 to your computer and use it in GitHub Desktop.
Get local IP addresses
Use net.InterfaceAddrs().
addrs, err := net.InterfaceAddrs()
if err != nil {
panic(err)
}
for i, addr := range addrs {
fmt.Printf("%d %v\n", i, addr)
}
If you want to know interface names too, use net.Interfaces() to get a list of interfaces first.
list, err := net.Interfaces()
if err != nil {
panic(err)
}
for i, iface := range list {
fmt.Printf("%d name=%s %v\n", i, iface.Name, iface)
addrs, err := iface.Addrs()
if err != nil {
panic(err)
}
for j, addr := range addrs {
fmt.Printf(" %d %v\n", j, addr)
}
}
#pkg~net
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment