netutils.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. return ip.IsPrivate()
  57. }
  58. // Check if an Ip string is ipv6
  59. func IsIPv6(ipStr string) bool {
  60. ip := net.ParseIP(ipStr)
  61. if ip == nil {
  62. return false
  63. }
  64. return ip.To4() == nil && ip.To16() != nil
  65. }