Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. package ipmath
  2.  
  3. import (
  4. "crypto/sha1"
  5. "encoding/binary"
  6. "math"
  7. "net"
  8. )
  9.  
  10. //ToUInt32 converts an IPv4 address into
  11. //a uint32
  12. func ToUInt32(ip net.IP) uint32 {
  13. buff := make([]byte, 4)
  14. copy(buff, []byte(ip))
  15. return binary.BigEndian.Uint32(buff)
  16. }
  17.  
  18. //FromUInt32 converts a uint32 into
  19. //an IPv4 address
  20. func FromUInt32(u uint32) net.IP {
  21. buff := make([]byte, 4)
  22. binary.BigEndian.PutUint32(buff, u)
  23. return net.IP(buff)
  24. }
  25.  
  26. //DeltaIP returns the IPv4 delta-many places away
  27. func DeltaIP(ip net.IP, delta int) net.IP {
  28. if delta == 0 {
  29. return ip
  30. }
  31. i := int64(ToUInt32(ip))
  32. i += int64(delta)
  33. if i > math.MaxUint32 {
  34. i = math.MaxUint32
  35. }
  36. return FromUInt32(uint32(i))
  37.  
  38. }
  39.  
  40. //NextIP returns the next IPv4 in sequence
  41. func NextIP(ip net.IP) net.IP {
  42. return DeltaIP(ip, 1)
  43. }
  44.  
  45. //PrevIP returns the previous IPv4 in sequence
  46. func PrevIP(ip net.IP) net.IP {
  47. return DeltaIP(ip, 1)
  48. }
  49.  
  50. //IsNetworkAddress returns whether the given IPv4 address
  51. //is the network address of the given IPv4 subnet
  52. func IsNetworkAddress(ip net.IP, network *net.IPNet) bool {
  53. curr := binary.BigEndian.Uint32([]byte(ip))
  54. mask := binary.BigEndian.Uint32([]byte(network.Mask))
  55. if mask == math.MaxUint32 {
  56. return false
  57. }
  58. return (^mask & curr) == uint32(0)
  59. }
  60.  
  61. //IsBroadcastAddress returns whether the given IPv4 address
  62. //is the broadcast address of the given IPv4 subnet
  63. func IsBroadcastAddress(ip net.IP, network *net.IPNet) bool {
  64. curr := binary.BigEndian.Uint32([]byte(ip))
  65. mask := binary.BigEndian.Uint32([]byte(network.Mask))
  66. if mask == math.MaxUint32 {
  67. return false
  68. }
  69. return (mask | curr) == math.MaxUint32
  70. }
  71.  
  72. //NetworkSize returns the number of addresses in a subnet
  73. func NetworkSize(network *net.IPNet) uint32 {
  74. mask := binary.BigEndian.Uint32([]byte(network.Mask))
  75. return ^mask
  76. }
  77.  
  78. //Hash an IP with SHA1
  79. func Hash(ip net.IP) []byte {
  80. input := []byte(ip.To4())
  81. h := sha1.New()
  82. h.Write(input)
  83. output := h.Sum(nil)
  84. return output
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement