geoloader.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package geodb
  2. import (
  3. "bytes"
  4. "net"
  5. )
  6. /*
  7. func (s *Store) search(ip string) (string, error) {
  8. parsedIP := net.ParseIP(ip).To4()
  9. if parsedIP == nil {
  10. return "", errors.New("invalid ip given")
  11. }
  12. a := int(parsedIP[0])
  13. b := int(parsedIP[1])
  14. //c := int(parsedIP[2])
  15. //d := int(parsedIP[3])
  16. //Offset A to match cloestes range
  17. for i := 0; i < 3; i++ {
  18. //Check if the root folder exists for A
  19. _, err := geoip.ReadDir("geoip/" + strconv.Itoa(a-i))
  20. if err == nil {
  21. a = a - i
  22. break
  23. }
  24. for j := b; j >= 0; j-- {
  25. _, err := geoip.Open("geoip/" + strconv.Itoa(a) + "/" + strconv.Itoa(j) + ".txt")
  26. if err == nil {
  27. b = j
  28. break
  29. }
  30. }
  31. ipDetails, err := geoip.ReadFile("geoip/" + strconv.Itoa(a) + "/" + strconv.Itoa(b) + ".txt")
  32. if err != nil {
  33. return "", err
  34. }
  35. lines := strings.Split(string(ipDetails), "\n")
  36. result := ""
  37. for _, record := range lines {
  38. c := strings.Split(record, ",")
  39. if len(c) != 3 {
  40. continue
  41. }
  42. ipStart := c[0]
  43. ipEnd := c[1]
  44. cc := c[2]
  45. fmt.Println(ipStart, ipEnd, cc)
  46. if isIPInRange(ip, ipStart, ipEnd) {
  47. //fmt.Println(">>>>", cc)
  48. result = cc
  49. }
  50. }
  51. return result, nil
  52. }
  53. */
  54. // Check if a ip string is within the range of two others
  55. func isIPInRange(ip, start, end string) bool {
  56. ipAddr := net.ParseIP(ip)
  57. if ipAddr == nil {
  58. return false
  59. }
  60. startAddr := net.ParseIP(start)
  61. if startAddr == nil {
  62. return false
  63. }
  64. endAddr := net.ParseIP(end)
  65. if endAddr == nil {
  66. return false
  67. }
  68. if ipAddr.To4() == nil || startAddr.To4() == nil || endAddr.To4() == nil {
  69. return false
  70. }
  71. return bytes.Compare(ipAddr.To4(), startAddr.To4()) >= 0 && bytes.Compare(ipAddr.To4(), endAddr.To4()) <= 0
  72. }