Skip to content

Instantly share code, notes, and snippets.

@neilco
Created November 21, 2013 14:52
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 neilco/7582916 to your computer and use it in GitHub Desktop.
Save neilco/7582916 to your computer and use it in GitHub Desktop.
Go function to return the first IPv4 address of the named interface
package net
import (
"net"
"os"
)
func InterfaceIPv4Address(name string) net.IP {
intf, err := net.InterfaceByName(name)
if err != nil {
os.Stderr.WriteString("Oops: " + err.Error() + "\n")
os.Exit(1)
}
addrs, _ := intf.Addrs()
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok {
if ipnet.IP.To4() != nil {
return ipnet.IP
}
}
}
return nil
}
package main
import (
"fmt"
"./net"
)
func main() {
// Print my WLAN IPv4 address
fmt.Println(net.InterfaceIPv4Address("en1").String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment