utils.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package ipam
  2. import (
  3. "fmt"
  4. "net"
  5. "github.com/docker/libnetwork/ipamapi"
  6. "github.com/docker/libnetwork/types"
  7. )
  8. type ipVersion int
  9. const (
  10. v4 = 4
  11. v6 = 6
  12. )
  13. func getAddressRange(pool string, masterNw *net.IPNet) (*AddressRange, error) {
  14. ip, nw, err := net.ParseCIDR(pool)
  15. if err != nil {
  16. return nil, ipamapi.ErrInvalidSubPool
  17. }
  18. lIP, e := types.GetHostPartIP(nw.IP, masterNw.Mask)
  19. if e != nil {
  20. return nil, fmt.Errorf("failed to compute range's lowest ip address: %v", e)
  21. }
  22. bIP, e := types.GetBroadcastIP(nw.IP, nw.Mask)
  23. if e != nil {
  24. return nil, fmt.Errorf("failed to compute range's broadcast ip address: %v", e)
  25. }
  26. hIP, e := types.GetHostPartIP(bIP, masterNw.Mask)
  27. if e != nil {
  28. return nil, fmt.Errorf("failed to compute range's highest ip address: %v", e)
  29. }
  30. nw.IP = ip
  31. return &AddressRange{nw, ipToUint64(types.GetMinimalIP(lIP)), ipToUint64(types.GetMinimalIP(hIP))}, nil
  32. }
  33. // It generates the ip address in the passed subnet specified by
  34. // the passed host address ordinal
  35. func generateAddress(ordinal uint64, network *net.IPNet) net.IP {
  36. var address [16]byte
  37. // Get network portion of IP
  38. if getAddressVersion(network.IP) == v4 {
  39. copy(address[:], network.IP.To4())
  40. } else {
  41. copy(address[:], network.IP)
  42. }
  43. end := len(network.Mask)
  44. addIntToIP(address[:end], ordinal)
  45. return net.IP(address[:end])
  46. }
  47. func getAddressVersion(ip net.IP) ipVersion {
  48. if ip.To4() == nil {
  49. return v6
  50. }
  51. return v4
  52. }
  53. // Adds the ordinal IP to the current array
  54. // 192.168.0.0 + 53 => 192.168.0.53
  55. func addIntToIP(array []byte, ordinal uint64) {
  56. for i := len(array) - 1; i >= 0; i-- {
  57. array[i] |= (byte)(ordinal & 0xff)
  58. ordinal >>= 8
  59. }
  60. }
  61. // Convert an ordinal to the respective IP address
  62. func ipToUint64(ip []byte) (value uint64) {
  63. cip := types.GetMinimalIP(ip)
  64. for i := 0; i < len(cip); i++ {
  65. j := len(cip) - 1 - i
  66. value += uint64(cip[i]) << uint(j*8)
  67. }
  68. return value
  69. }