Last active
November 3, 2015 18:18
-
-
Save rsmoorthy/1459816c138dc2e09768 to your computer and use it in GitHub Desktop.
Go: Match any interfaces/IP address for the corresponding CIDR provided
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 ( | |
"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