slowSearch.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package geodb
  2. import (
  3. "errors"
  4. "math/big"
  5. "net"
  6. )
  7. /*
  8. slowSearch.go
  9. This script implement the slow search method for ip to country code
  10. lookup. If you have the memory allocation for near O(1) lookup,
  11. you should not be using slow search mode.
  12. */
  13. func ipv4ToUInt32(ip net.IP) uint32 {
  14. ip = ip.To4()
  15. return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
  16. }
  17. func isIPv4InRange(startIP, endIP, testIP string) (bool, error) {
  18. start := net.ParseIP(startIP)
  19. end := net.ParseIP(endIP)
  20. test := net.ParseIP(testIP)
  21. if start == nil || end == nil || test == nil {
  22. return false, errors.New("invalid IP address format")
  23. }
  24. startUint := ipv4ToUInt32(start)
  25. endUint := ipv4ToUInt32(end)
  26. testUint := ipv4ToUInt32(test)
  27. return testUint >= startUint && testUint <= endUint, nil
  28. }
  29. func isIPv6InRange(startIP, endIP, testIP string) (bool, error) {
  30. start := net.ParseIP(startIP)
  31. end := net.ParseIP(endIP)
  32. test := net.ParseIP(testIP)
  33. if start == nil || end == nil || test == nil {
  34. return false, errors.New("invalid IP address format")
  35. }
  36. startInt := new(big.Int).SetBytes(start.To16())
  37. endInt := new(big.Int).SetBytes(end.To16())
  38. testInt := new(big.Int).SetBytes(test.To16())
  39. return testInt.Cmp(startInt) >= 0 && testInt.Cmp(endInt) <= 0, nil
  40. }
  41. // Slow country code lookup for
  42. func (s *Store) slowSearchIpv4(ipAddr string) string {
  43. if isReservedIP(ipAddr) {
  44. return ""
  45. }
  46. for _, ipRange := range s.geodb {
  47. startIp := ipRange[0]
  48. endIp := ipRange[1]
  49. cc := ipRange[2]
  50. inRange, _ := isIPv4InRange(startIp, endIp, ipAddr)
  51. if inRange {
  52. return cc
  53. }
  54. }
  55. return ""
  56. }
  57. func (s *Store) slowSearchIpv6(ipAddr string) string {
  58. if isReservedIP(ipAddr) {
  59. return ""
  60. }
  61. for _, ipRange := range s.geodbIpv6 {
  62. startIp := ipRange[0]
  63. endIp := ipRange[1]
  64. cc := ipRange[2]
  65. inRange, _ := isIPv6InRange(startIp, endIp, ipAddr)
  66. if inRange {
  67. return cc
  68. }
  69. }
  70. return ""
  71. }