Created
November 21, 2013 14:52
-
-
Save neilco/7582916 to your computer and use it in GitHub Desktop.
Go function to return the first IPv4 address of the named interface
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
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 | |
} |
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
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