utils.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Package ipamutils provides utility functions for ipam management
  2. package ipamutils
  3. import (
  4. "net"
  5. "sync"
  6. )
  7. var (
  8. // PredefinedBroadNetworks contains a list of 31 IPv4 private networks with host size 16 and 12
  9. // (172.17-31.x.x/16, 192.168.x.x/20) which do not overlap with the networks in `PredefinedGranularNetworks`
  10. PredefinedBroadNetworks []*net.IPNet
  11. // PredefinedGranularNetworks contains a list of 64K IPv4 private networks with host size 8
  12. // (10.x.x.x/24) which do not overlap with the networks in `PredefinedBroadNetworks`
  13. PredefinedGranularNetworks []*net.IPNet
  14. initNetworksOnce sync.Once
  15. )
  16. // InitNetworks initializes the pre-defined networks used by the built-in IP allocator
  17. func InitNetworks() {
  18. initNetworksOnce.Do(func() {
  19. PredefinedBroadNetworks = initBroadPredefinedNetworks()
  20. PredefinedGranularNetworks = initGranularPredefinedNetworks()
  21. })
  22. }
  23. func initBroadPredefinedNetworks() []*net.IPNet {
  24. pl := make([]*net.IPNet, 0, 31)
  25. mask := []byte{255, 255, 0, 0}
  26. for i := 17; i < 32; i++ {
  27. pl = append(pl, &net.IPNet{IP: []byte{172, byte(i), 0, 0}, Mask: mask})
  28. }
  29. mask20 := []byte{255, 255, 240, 0}
  30. for i := 0; i < 16; i++ {
  31. pl = append(pl, &net.IPNet{IP: []byte{192, 168, byte(i << 4), 0}, Mask: mask20})
  32. }
  33. return pl
  34. }
  35. func initGranularPredefinedNetworks() []*net.IPNet {
  36. pl := make([]*net.IPNet, 0, 256*256)
  37. mask := []byte{255, 255, 255, 0}
  38. for i := 0; i < 256; i++ {
  39. for j := 0; j < 256; j++ {
  40. pl = append(pl, &net.IPNet{IP: []byte{10, byte(i), byte(j), 0}, Mask: mask})
  41. }
  42. }
  43. return pl
  44. }