helpers.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package dhcp4
  2. import (
  3. "encoding/binary"
  4. "net"
  5. "time"
  6. )
  7. // IPRange returns how many ips in the ip range from start to stop (inclusive)
  8. func IPRange(start, stop net.IP) int {
  9. //return int(Uint([]byte(stop))-Uint([]byte(start))) + 1
  10. return int(binary.BigEndian.Uint32(stop.To4())) - int(binary.BigEndian.Uint32(start.To4())) + 1
  11. }
  12. // IPAdd returns a copy of start + add.
  13. // IPAdd(net.IP{192,168,1,1},30) returns net.IP{192.168.1.31}
  14. func IPAdd(start net.IP, add int) net.IP { // IPv4 only
  15. start = start.To4()
  16. //v := Uvarint([]byte(start))
  17. result := make(net.IP, 4)
  18. binary.BigEndian.PutUint32(result, binary.BigEndian.Uint32(start)+uint32(add))
  19. //PutUint([]byte(result), v+uint64(add))
  20. return result
  21. }
  22. // IPLess returns where IP a is less than IP b.
  23. func IPLess(a, b net.IP) bool {
  24. b = b.To4()
  25. for i, ai := range a.To4() {
  26. if ai != b[i] {
  27. return ai < b[i]
  28. }
  29. }
  30. return false
  31. }
  32. // IPInRange returns true if ip is between (inclusive) start and stop.
  33. func IPInRange(start, stop, ip net.IP) bool {
  34. return !(IPLess(ip, start) || IPLess(stop, ip))
  35. }
  36. // OptionsLeaseTime - converts a time.Duration to a 4 byte slice, compatible
  37. // with OptionIPAddressLeaseTime.
  38. func OptionsLeaseTime(d time.Duration) []byte {
  39. leaseBytes := make([]byte, 4)
  40. binary.BigEndian.PutUint32(leaseBytes, uint32(d/time.Second))
  41. //PutUvarint(leaseBytes, uint64(d/time.Second))
  42. return leaseBytes
  43. }
  44. // JoinIPs returns a byte slice of IP addresses, one immediately after the other
  45. // This may be useful for creating multiple IP options such as OptionRouter.
  46. func JoinIPs(ips []net.IP) (b []byte) {
  47. for _, v := range ips {
  48. b = append(b, v.To4()...)
  49. }
  50. return
  51. }