ip.go 759 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package ip
  2. import "net"
  3. var PRIVATE_NETWORKS = [...]string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fd00::/8", "127.0.0.0/8"}
  4. type IP struct {
  5. IP net.IP
  6. private_networks []*net.IPNet
  7. }
  8. func NewIP() *IP {
  9. var ipnet *net.IPNet
  10. privnets := make([]*net.IPNet, len(PRIVATE_NETWORKS), len(PRIVATE_NETWORKS))
  11. for i, n := range PRIVATE_NETWORKS {
  12. _, ipnet, _ = net.ParseCIDR(n)
  13. privnets[i] = ipnet
  14. }
  15. return &IP{private_networks: privnets}
  16. }
  17. func (i *IP) IsPrivate(ip net.IP) bool {
  18. for _, net := range i.private_networks {
  19. if net.Contains(ip) {
  20. return true
  21. }
  22. }
  23. return false
  24. }
  25. func (i *IP) Network(ip net.IP) *net.IPNet {
  26. for _, n := range i.private_networks {
  27. if n.Contains(ip) {
  28. return n
  29. }
  30. }
  31. return nil
  32. }