Skip to content

Instantly share code, notes, and snippets.

@mazieres
Created September 29, 2016 07:19
Show Gist options
  • Save mazieres/112306a6d3ecaf73ec64930fdf180be9 to your computer and use it in GitHub Desktop.
Save mazieres/112306a6d3ecaf73ec64930fdf180be9 to your computer and use it in GitHub Desktop.
Lookup the location attributed to an IP by IP2Location Lite Country DB (https://lite.ip2location.com/database/ip-country)
package main
import (
"bufio"
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"os"
"sort"
"strconv"
"strings"
)
func ipStrToInt(ipStr string) (int, error) {
ipArr := strings.Split(ipStr, ".")
if len(ipArr) != 4 {
err := errors.New("IP not valid: length not 4")
return -1, err
}
var ipInt int
for idx, elem := range ipArr {
elemInt, err := strconv.Atoi(elem)
if err != nil {
log.Print("IP not valid: couldn't convert to Int")
return -1, err
}
switch idx {
case 0:
ipInt += elemInt * 16777216
case 1:
ipInt += elemInt * 65536
case 2:
ipInt += elemInt * 256
case 3:
ipInt += elemInt
}
}
return ipInt, nil
}
func loadIP2LocationLiteDB(path string) (ranges []int, countries []string, err error) {
f, err := os.Open(path)
if err != nil {
log.Print("error opening")
return nil, nil, err
}
defer f.Close()
r := csv.NewReader(bufio.NewReader(f))
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, nil, err
}
rangeInt, err := strconv.Atoi(record[0])
if err != nil {
return nil, nil, err
}
rangeInt--
ranges = append(ranges, rangeInt)
countries = append(countries, record[3])
}
return ranges, countries, nil
}
func ipCountryLookup(ip string, ranges []int, countries []string) (string, error) {
n, err := ipStrToInt(ip)
if err != nil {
log.Print(err)
return "", err
}
return countries[sort.SearchInts(ranges, n)], nil
}
func main() {
ranges, countries, err := loadIP2LocationLiteDB("./IP2LOCATION-LITE-DB1.CSV")
if err != nil {
log.Print(err)
return
}
ipStr := "163.172.164.39"
country, err := ipCountryLookup(ipStr, ranges, countries)
if err != nil {
log.Print(err)
return
}
fmt.Println(country)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment