Skip to content

Instantly share code, notes, and snippets.

@lapnd
Created December 8, 2018 15:33
Show Gist options
  • Save lapnd/2a79f268eb89ff838c012c3494bb5012 to your computer and use it in GitHub Desktop.
Save lapnd/2a79f268eb89ff838c012c3494bb5012 to your computer and use it in GitHub Desktop.
Example of getting the IP and netmask of an interface with Golang
package main
import (
"fmt"
"net"
"os"
)
func main() {
mgmtInterface, err := net.InterfaceByName("ens160")
if err != nil {
fmt.Println("Unable to find interface")
os.Exit(-1)
}
addrs, err := mgmtInterface.Addrs()
if err != nil {
fmt.Println("Interface has no address")
os.Exit(-1)
}
for _, addr := range addrs {
var ip net.IP
var mask net.IPMask
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
mask = v.Mask
case *net.IPAddr:
ip = v.IP
mask = ip.DefaultMask()
}
if ip == nil {
continue
}
ip = ip.To4()
if ip == nil {
continue
}
cleanMask := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
fmt.Println(ip, cleanMask)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment