Skip to content

Instantly share code, notes, and snippets.

@polynomialspace
Last active May 31, 2021 22:03
Show Gist options
  • Save polynomialspace/589346543a489d145e6e257afdad1b7d to your computer and use it in GitHub Desktop.
Save polynomialspace/589346543a489d145e6e257afdad1b7d to your computer and use it in GitHub Desktop.
idk
// go get "inet.af/netaddr"
// echo '[ "208.80.44.0/22", "208.80.44.0/23", "208.80.44.0/24", "208.80.45.0/24", "208.80.46.0/23", "208.80.46.0/24", "208.80.47.0/24" ]' | go run main.go -json -
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strings"
"inet.af/netaddr"
)
var (
invalidIPSet = errors.New("invalid IP set")
)
func Aggregate(ranges []string) ([]netaddr.IPPrefix, error) {
ipsb := new(netaddr.IPSetBuilder)
for _, r := range ranges {
_, network, err := net.ParseCIDR(r)
if err != nil {
return nil, err
}
prefix, ok := netaddr.FromStdIPNet(network)
if !ok {
return nil, fmt.Errorf("%v: %w", r, invalidIPSet)
}
ipsb.AddPrefix(prefix)
}
return ipsb.IPSet().Prefixes(), nil
}
func Fatalln(v ...interface{}) {
fmt.Fprintln(os.Stderr, v...)
os.Exit(1)
}
func main() {
var useJSON bool
flag.BoolVar(&useJSON, "json", false, "parse input as json")
flag.Parse()
var in io.ReadCloser
filename := flag.Arg(0)
switch filename {
case "-", "":
in = os.Stdin
default:
var err error
in, err = os.Open(filename)
if err != nil {
Fatalln(err)
}
defer in.Close()
}
data, err := ioutil.ReadAll(in)
if err != nil {
Fatalln(err)
}
var ranges []string
if useJSON {
err = json.Unmarshal(data, &ranges)
if err != nil {
Fatalln(err)
}
} else {
ranges = strings.Fields(string(data))
}
aggregated, err := Aggregate(ranges)
if err != nil {
Fatalln(err)
}
if useJSON {
out := json.NewEncoder(os.Stdout)
out.Encode(aggregated)
} else {
for _, agg := range aggregated {
fmt.Println(agg)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment