Skip to content

Instantly share code, notes, and snippets.

@se77en se77en/IsPrivateIP.go forked from mapix/IsPrivateIP.go
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.