ips.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package ips
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/seancfoley/ipaddress-go/ipaddr"
  6. )
  7. // GetFirstAddr - gets the first valid address in a given IPv4 CIDR
  8. func GetFirstAddr(cidr4 string) (*ipaddr.IPAddress, error) {
  9. currentCidr := ipaddr.NewIPAddressString(cidr4).GetAddress()
  10. if !currentCidr.IsIPv4() {
  11. return nil, fmt.Errorf("invalid IPv4 CIDR provided to GetFirstAddr")
  12. }
  13. lower := currentCidr.GetLower()
  14. ipParts := strings.Split(lower.GetNetIPAddr().IP.String(), ".")
  15. if ipParts[len(ipParts)-1] == "0" {
  16. lower = lower.Increment(1)
  17. }
  18. return lower, nil
  19. }
  20. // GetLastAddr - gets the last valid address in a given IPv4 CIDR
  21. func GetLastAddr(cidr4 string) (*ipaddr.IPAddress, error) {
  22. currentCidr := ipaddr.NewIPAddressString(cidr4).GetAddress()
  23. if !currentCidr.IsIPv4() {
  24. return nil, fmt.Errorf("invalid IPv4 CIDR provided to GetLastAddr")
  25. }
  26. upper := currentCidr.GetUpper()
  27. ipParts := strings.Split(upper.GetNetIPAddr().IP.String(), ".")
  28. if ipParts[len(ipParts)-1] == "255" {
  29. upper = upper.Increment(-1)
  30. }
  31. return upper, nil
  32. }
  33. // GetFirstAddr6 - gets the first valid IPv6 address in a given IPv6 CIDR
  34. func GetFirstAddr6(cidr6 string) (*ipaddr.IPAddress, error) {
  35. currentCidr := ipaddr.NewIPAddressString(cidr6).GetAddress()
  36. if !currentCidr.IsIPv6() {
  37. return nil, fmt.Errorf("invalid IPv6 CIDR provided to GetFirstAddr6")
  38. }
  39. lower := currentCidr.GetLower()
  40. ipParts := strings.Split(lower.GetNetIPAddr().IP.String(), "::")
  41. if len(ipParts) == 2 {
  42. if len(ipParts[len(ipParts)-1]) == 0 {
  43. lower = lower.Increment(1)
  44. }
  45. }
  46. return lower, nil
  47. }
  48. // GetLastAddr6 - gets the last valid IPv6 address in a given IPv6 CIDR
  49. func GetLastAddr6(cidr6 string) (*ipaddr.IPAddress, error) {
  50. currentCidr := ipaddr.NewIPAddressString(cidr6).GetAddress()
  51. if !currentCidr.IsIPv6() {
  52. return nil, fmt.Errorf("invalid IPv6 CIDR provided to GetLastAddr6")
  53. }
  54. upper := currentCidr.GetUpper()
  55. return upper, nil
  56. }