cidr.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2015 CNI authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ip
  15. import (
  16. "math/big"
  17. "net"
  18. )
  19. // NextIP returns IP incremented by 1
  20. func NextIP(ip net.IP) net.IP {
  21. i := ipToInt(ip)
  22. return intToIP(i.Add(i, big.NewInt(1)))
  23. }
  24. // PrevIP returns IP decremented by 1
  25. func PrevIP(ip net.IP) net.IP {
  26. i := ipToInt(ip)
  27. return intToIP(i.Sub(i, big.NewInt(1)))
  28. }
  29. func ipToInt(ip net.IP) *big.Int {
  30. if v := ip.To4(); v != nil {
  31. return big.NewInt(0).SetBytes(v)
  32. }
  33. return big.NewInt(0).SetBytes(ip.To16())
  34. }
  35. func intToIP(i *big.Int) net.IP {
  36. return net.IP(i.Bytes())
  37. }
  38. // Network masks off the host portion of the IP
  39. func Network(ipn *net.IPNet) *net.IPNet {
  40. return &net.IPNet{
  41. IP: ipn.IP.Mask(ipn.Mask),
  42. Mask: ipn.Mask,
  43. }
  44. }