Skip to content

Instantly share code, notes, and snippets.

@se77en
Forked from mapix/IsPrivateIP.go
Last active August 29, 2015 14:15
Show Gist options
  • Save se77en/e8da113b0c7df3491f76 to your computer and use it in GitHub Desktop.
Save se77en/e8da113b0c7df3491f76 to your computer and use it in GitHub Desktop.
package main
import "net"
import "fmt"
func main() {
fmt.Println(IsPrivateIP("111.11.191.17"))
fmt.Println(IsPrivateIP("192.168.0.100"))
fmt.Println(IsPrivateIP("10.0.8.100"))
}
var PrivateBlocks []*net.IPNet
func IsPrivateIP(ip_str string) bool {
if PrivateBlocks == nil {
// Add each private block
PrivateBlocks = make([]*net.IPNet, 3)
_, block, err := net.ParseCIDR("10.0.0.0/8")
if err != nil {
panic(fmt.Sprintf("Bad cidr. Got %v", err))
}
PrivateBlocks[0] = block
_, block, err = net.ParseCIDR("172.16.0.0/12")
if err != nil {
panic(fmt.Sprintf("Bad cidr. Got %v", err))
}
PrivateBlocks[1] = block
_, block, err = net.ParseCIDR("192.168.0.0/16")
if err != nil {
panic(fmt.Sprintf("Bad cidr. Got %v", err))
}
PrivateBlocks[2] = block
_, block, err = net.ParseCIDR("127.0.0.0/8")
if err != nil {
panic(fmt.Sprintf("Bad cidr. Got %v", err))
}
}
ip := net.ParseIP(ip_str)
for _, priv := range PrivateBlocks {
if priv.Contains(ip) {
return true
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment