Skip to content

Instantly share code, notes, and snippets.

@abh
Last active October 14, 2015 01:07
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 abh/4283789 to your computer and use it in GitHub Desktop.
Save abh/4283789 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/miekg/bitradix"
"net"
"reflect"
)
type ASN uint32
func IPToUint(ip net.IP) (i uint64) {
ip = ip.To4()
fv := reflect.ValueOf(&i).Elem()
fv.SetUint(uint64(uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[+3])))
fmt.Printf("%s becomes %d\n", ip.String(), i)
return
}
func AddRouteString(t *bitradix.Radix, s string, asn ASN) {
fmt.Println("Adding route for", s)
_, ipnet, err := net.ParseCIDR(s)
if err != nil {
panic("bad network")
}
fmt.Printf("ipnet %#v\n", ipnet)
fmt.Printf("ip %#v\n", ipnet.IP)
ip := IPToUint(ipnet.IP)
fmt.Printf("inserting ip %#v\n", ip)
t.Insert(ip, uint32(asn))
}
func FindRoute(t *bitradix.Radix, ipStr string) int {
fmt.Println("=== Looking for route for", ipStr)
_, target, err := net.ParseCIDR(ipStr)
if err != nil {
panic("could not parse target")
}
iTarget := IPToUint(target.IP)
node, asn := t.Find(iTarget)
fmt.Println("Found node", node, "ASN", asn)
return asn
}
func check(tree *bitradix.Radix, s string, expected_asn int) {
asn := FindRoute(tree, s)
fmt.Println("= Got ASN", asn, "expected", expected_asn)
if asn != expected_asn {
// panic("wrong asn")
}
}
func main() {
tree := bitradix.New()
AddRouteString(tree, "10.0.0.2/8", 10)
AddRouteString(tree, "10.20.0.0/14", 20)
AddRouteString(tree, "10.21.0.0/16", 21)
AddRouteString(tree, "192.168.0.0/16", 192)
AddRouteString(tree, "192.168.2.0/24", 1922)
check(tree, "10.20.1.2/32", 20)
check(tree, "10.22.1.2/32", 20)
check(tree, "10.19.0.1/32", 10)
check(tree, "10.21.0.1/32", 21)
check(tree, "192.168.2.3/32", 1922)
check(tree, "230.0.0.1/32", 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment