12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package geodb
- import (
- "bytes"
- "net"
- )
- /*
- func (s *Store) search(ip string) (string, error) {
- parsedIP := net.ParseIP(ip).To4()
- if parsedIP == nil {
- return "", errors.New("invalid ip given")
- }
- a := int(parsedIP[0])
- b := int(parsedIP[1])
- //c := int(parsedIP[2])
- //d := int(parsedIP[3])
- //Offset A to match cloestes range
- for i := 0; i < 3; i++ {
- //Check if the root folder exists for A
- _, err := geoip.ReadDir("geoip/" + strconv.Itoa(a-i))
- if err == nil {
- a = a - i
- break
- }
- for j := b; j >= 0; j-- {
- _, err := geoip.Open("geoip/" + strconv.Itoa(a) + "/" + strconv.Itoa(j) + ".txt")
- if err == nil {
- b = j
- break
- }
- }
- ipDetails, err := geoip.ReadFile("geoip/" + strconv.Itoa(a) + "/" + strconv.Itoa(b) + ".txt")
- if err != nil {
- return "", err
- }
- lines := strings.Split(string(ipDetails), "\n")
- result := ""
- for _, record := range lines {
- c := strings.Split(record, ",")
- if len(c) != 3 {
- continue
- }
- ipStart := c[0]
- ipEnd := c[1]
- cc := c[2]
- fmt.Println(ipStart, ipEnd, cc)
- if isIPInRange(ip, ipStart, ipEnd) {
- //fmt.Println(">>>>", cc)
- result = cc
- }
- }
- return result, nil
- }
- */
- // Check if a ip string is within the range of two others
- func isIPInRange(ip, start, end string) bool {
- ipAddr := net.ParseIP(ip)
- if ipAddr == nil {
- return false
- }
- startAddr := net.ParseIP(start)
- if startAddr == nil {
- return false
- }
- endAddr := net.ParseIP(end)
- if endAddr == nil {
- return false
- }
- if ipAddr.To4() == nil || startAddr.To4() == nil || endAddr.To4() == nil {
- return false
- }
- return bytes.Compare(ipAddr.To4(), startAddr.To4()) >= 0 && bytes.Compare(ipAddr.To4(), endAddr.To4()) <= 0
- }
|