Skip to content

Instantly share code, notes, and snippets.

@tanis2000
Created March 22, 2021 13: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 tanis2000/1609f5455ec6150dfebf22615e0f4f5e to your computer and use it in GitHub Desktop.
Save tanis2000/1609f5455ec6150dfebf22615e0f4f5e 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