Skip to content

Instantly share code, notes, and snippets.

@rsmoorthy
Last active November 3, 2015 18:18
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 rsmoorthy/1459816c138dc2e09768 to your computer and use it in GitHub Desktop.
Save rsmoorthy/1459816c138dc2e09768 to your computer and use it in GitHub Desktop.
Go: Match any interfaces/IP address for the corresponding CIDR provided
package main
import (
"net"
"fmt"
)
func matchCIDR(in_cidr string) (bool) {
_, in_net, err := net.ParseCIDR(in_cidr)
if err != nil {
fmt.Printf("Invalid CIDR parsed")
return false
}
ifaces, err := net.Interfaces()
if err != nil {
fmt.Printf("Interfaces returned empty")
return false
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
fmt.Printf("Address for interface gave error")
continue
}
for _, addr := range addrs {
ip, ipnet, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
if ip.To4() == nil {
continue
}
if ipnet.String() == in_net.String() {
fmt.Printf("Incoming CIDR matched with Intf:%s IP:%s\n", i.Name, ip.String())
return true
}
}
}
return false
}
func main() {
var in_cidr string = "192.168.0.1/24"
if matchCIDR(in_cidr) {
fmt.Println("Matched")
} else {
fmt.Printf("No networks matched the current system for the network %s\n", in_cidr)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment