Skip to content

Instantly share code, notes, and snippets.

@miekg
Created January 7, 2013 15:10
Show Gist options
  • Save miekg/4475669 to your computer and use it in GitHub Desktop.
Save miekg/4475669 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"github.com/miekg/bitradix"
"log"
"net"
"os"
"reflect"
)
func main() {
r32 := bitradix.New32()
dec := json.NewDecoder(os.Stdin)
for {
var v map[string]interface{}
if err := dec.Decode(&v); err != nil {
log.Println(err)
break
}
for _, v1 := range v {
for ip, v2 := range v1.(map[string]interface{}) {
addRoute(r32, ip, uint32(v2.(float64)))
}
}
}
// uncomment to print
// r32.Do(func(r1 *bitradix.Radix32, i int) { log.Printf("(%2d): %032b/%d -> %d\n", i, r1.Key(), r1.Bits(), r1.Value) })
}
func ipToUint(n *net.IPNet) (i uint32, mask int) {
ip := n.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])))
mask, _ = n.Mask.Size()
return
}
func addRoute(r *bitradix.Radix32, s string, asn uint32) {
_, ipnet, err := net.ParseCIDR(s)
if err != nil {
log.Println(err)
return
}
net, mask := ipToUint(ipnet)
r.Insert(net, mask, asn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment