Skip to content

Instantly share code, notes, and snippets.

@zeisss
Last active June 22, 2021 13:47
Show Gist options
  • Save zeisss/b4f3c6673912a030a0b69c0510f80d15 to your computer and use it in GitHub Desktop.
Save zeisss/b4f3c6673912a030a0b69c0510f80d15 to your computer and use it in GitHub Desktop.
AWS ip-ranges.json: Find aws prefix / CIDR block for given IP addresses
/*
find_ip search a local copy of https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html#aws-ip-download for a specific IP and prints the prefix.
*/
package main
import (
"encoding/json"
"fmt"
"net"
"os"
)
type IPRangesFile struct {
Prefixes []Prefix
}
type Prefix struct {
IPPrefix string `json:"ip_prefix"`
Region string
Service string
NetworkBorderGroup string
}
func loadIPRangesFile(file string) (IPRangesFile, error) {
fp, err := os.Open(file)
if err != nil {
return IPRangesFile{}, err
}
defer fp.Close()
var ipranges IPRangesFile
err = json.NewDecoder(fp).Decode(&ipranges)
return ipranges, err
}
func findPrefix(ipranges IPRangesFile, needle string) (Prefix, bool) {
ip := net.ParseIP(needle)
for _, prefix := range ipranges.Prefixes {
_, cidr, err := net.ParseCIDR(prefix.IPPrefix)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Ignoring prefix with invalid cidr: %s\n", prefix.IPPrefix)
continue
}
if cidr.Contains(ip) {
return prefix, true
}
}
return Prefix{}, false
}
func main() {
if len(os.Args) <= 2 {
fmt.Fprintf(os.Stderr, "Usage: find_ip FILE IP1, [IP2, ...]\n")
os.Exit(1)
}
ipranges, err := loadIPRangesFile(os.Args[1])
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
os.Exit(1)
}
for _, ip := range os.Args[2:] {
prefix, ok := findPrefix(ipranges, ip)
if ok {
fmt.Printf("%#v\n", prefix)
} else {
fmt.Fprintf(os.Stderr, "not found\n")
os.Exit(1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment