netutils.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package geodb
  2. import (
  3. "net"
  4. "net/http"
  5. "strings"
  6. )
  7. // Utilities function
  8. func GetRequesterIP(r *http.Request) string {
  9. ip := r.Header.Get("X-Forwarded-For")
  10. if ip == "" {
  11. ip = r.Header.Get("X-Real-IP")
  12. if ip == "" {
  13. ip = strings.Split(r.RemoteAddr, ":")[0]
  14. }
  15. }
  16. return ip
  17. }
  18. // Match the IP address with a wildcard string
  19. func MatchIpWildcard(ipAddress, wildcard string) bool {
  20. // Split IP address and wildcard into octets
  21. ipOctets := strings.Split(ipAddress, ".")
  22. wildcardOctets := strings.Split(wildcard, ".")
  23. // Check that both have 4 octets
  24. if len(ipOctets) != 4 || len(wildcardOctets) != 4 {
  25. return false
  26. }
  27. // Check each octet to see if it matches the wildcard or is an exact match
  28. for i := 0; i < 4; i++ {
  29. if wildcardOctets[i] == "*" {
  30. continue
  31. }
  32. if ipOctets[i] != wildcardOctets[i] {
  33. return false
  34. }
  35. }
  36. return true
  37. }
  38. // Match ip address with CIDR
  39. func MatchIpCIDR(ip string, cidr string) bool {
  40. // parse the CIDR string
  41. _, cidrnet, err := net.ParseCIDR(cidr)
  42. if err != nil {
  43. return false
  44. }
  45. // parse the IP address
  46. ipAddr := net.ParseIP(ip)
  47. // check if the IP address is within the CIDR range
  48. return cidrnet.Contains(ipAddr)
  49. }
  50. // Check if a ip is private IP range
  51. func IsPrivateIP(ipStr string) bool {
  52. ip := net.ParseIP(ipStr)
  53. if ip == nil {
  54. return false
  55. }
  56. // Check for IPv4 private address ranges
  57. if ip.To4() != nil {
  58. privateIPv4Ranges := []string{
  59. "10.0.0.0/8", // 10.0.0.0 - 10.255.255.255
  60. "172.16.0.0/12", // 172.16.0.0 - 172.31.255.255
  61. "192.168.0.0/16", // 192.168.0.0 - 192.168.255.255
  62. "169.254.0.0/16", // 169.254.0.0 - 169.254.255.255 (link-local addresses)
  63. }
  64. for _, network := range privateIPv4Ranges {
  65. _, privateNet, _ := net.ParseCIDR(network)
  66. if privateNet.Contains(ip) {
  67. return true
  68. }
  69. }
  70. } else {
  71. // Check for IPv6 private address ranges
  72. privateIPv6Ranges := []string{
  73. "fc00::/7", // Unique local addresses
  74. "fe80::/10", // Link-local addresses
  75. }
  76. for _, network := range privateIPv6Ranges {
  77. _, privateNet, _ := net.ParseCIDR(network)
  78. if privateNet.Contains(ip) {
  79. return true
  80. }
  81. }
  82. }
  83. return false
  84. }