Skip to content

Instantly share code, notes, and snippets.

@laybatin
Created September 16, 2019 00:23
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 laybatin/27c6f57d27d192193ea682eb255412b4 to your computer and use it in GitHub Desktop.
Save laybatin/27c6f57d27d192193ea682eb255412b4 to your computer and use it in GitHub Desktop.
Get Network Interfaces
package main
import (
"net"
"fmt"
"regexp"
"strings"
)
var tempInterfacesConfig string
var targetInterface string
func validIP4(ipAddress string) bool {
ipAddress = strings.Trim(ipAddress, " ")
re, _ := regexp.Compile(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`)
if re.MatchString(ipAddress) {
return true
}
return false
}
func LoadInterfaces() []string {
var ifaceList []string
ifaces, err := net.Interfaces()
if err != nil {
fmt.Print("localAddresses: %+v\n", err.Error())
return ifaceList
}
for _, i := range ifaces {
iface := i.Name
addrs, err := i.Addrs()
if err != nil {
fmt.Print("localAddresses: %+v\n", err.Error())
continue
}
for _, a := range addrs {
switch v := a.(type) {
case *net.IPAddr:
iface = fmt.Sprintf("%v : %s (%s)", i.Name, v.IP, v.IP.DefaultMask())
case *net.IPNet:
if !v.IP.IsLoopback() {
if v.IP.To4() != nil {
iface = fmt.Sprintf("%v : %s [%v/%v]", i.Name, v, v.IP.String(), v.Mask)
}
}
default:
iface = iface + "None"
}
}
ifaceList = append(ifaceList, iface)
}
return ifaceList
}
func main() {
list := LoadInterfaces()
for _,v := range list {
fmt.Println(v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment