Created
January 19, 2021 02:19
-
-
Save nanmu42/9c8139e15542b3c4a1709cb9e9ac61eb to your computer and use it in GitHub Desktop.
Golang: check if IP address is private
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// source: https://stackoverflow.com/questions/41240761/check-if-ip-address-is-in-private-network-space | |
var privateIPBlocks []*net.IPNet | |
func init() { | |
for _, cidr := range []string{ | |
"127.0.0.0/8", // IPv4 loopback | |
"10.0.0.0/8", // RFC1918 | |
"172.16.0.0/12", // RFC1918 | |
"192.168.0.0/16", // RFC1918 | |
"169.254.0.0/16", // RFC3927 link-local | |
"::1/128", // IPv6 loopback | |
"fe80::/10", // IPv6 link-local | |
"fc00::/7", // IPv6 unique local addr | |
} { | |
_, block, err := net.ParseCIDR(cidr) | |
if err != nil { | |
panic(fmt.Errorf("parse error on %q: %v", cidr, err)) | |
} | |
privateIPBlocks = append(privateIPBlocks, block) | |
} | |
} | |
func isPrivateIP(ip net.IP) bool { | |
if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() { | |
return true | |
} | |
for _, block := range privateIPBlocks { | |
if block.Contains(ip) { | |
return true | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment