wrangling.go 852 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package cidr
  2. import (
  3. "fmt"
  4. "math/big"
  5. "net"
  6. )
  7. func ipToInt(ip net.IP) (*big.Int, int) {
  8. val := &big.Int{}
  9. val.SetBytes([]byte(ip))
  10. if len(ip) == net.IPv4len {
  11. return val, 32
  12. } else if len(ip) == net.IPv6len {
  13. return val, 128
  14. } else {
  15. panic(fmt.Errorf("Unsupported address length %d", len(ip)))
  16. }
  17. }
  18. func intToIP(ipInt *big.Int, bits int) net.IP {
  19. ipBytes := ipInt.Bytes()
  20. ret := make([]byte, bits/8)
  21. // Pack our IP bytes into the end of the return array,
  22. // since big.Int.Bytes() removes front zero padding.
  23. for i := 1; i <= len(ipBytes); i++ {
  24. ret[len(ret)-i] = ipBytes[len(ipBytes)-i]
  25. }
  26. return net.IP(ret)
  27. }
  28. func insertNumIntoIP(ip net.IP, bigNum *big.Int, prefixLen int) net.IP {
  29. ipInt, totalBits := ipToInt(ip)
  30. bigNum.Lsh(bigNum, uint(totalBits-prefixLen))
  31. ipInt.Or(ipInt, bigNum)
  32. return intToIP(ipInt, totalBits)
  33. }