Skip to content

Instantly share code, notes, and snippets.

@sysr-q
Created June 28, 2013 06:33
Show Gist options
  • Save sysr-q/5882877 to your computer and use it in GitHub Desktop.
Save sysr-q/5882877 to your computer and use it in GitHub Desktop.
Horrible, I know. Don't judge me.
import struct, socket, csv
def ip_to_decimal(ip):
return struct.unpack("!I", socket.inet_aton(ip))[0]
def read_list(ip_csv="/tmp/IpToCountry.csv"):
""" Read the entire IpToCountry CSV file into life.
:param ip_csv: the file we're reading from
"""
lookup = []
with open(ip_csv, 'rb') as f:
reader = csv.reader(f)
for line in reader:
# The devil reincarnate catching us up
if len(line) != 7 or line[0].startswith('#'):
continue
lookup.append({
"from": int(line[0]),
"to": int(line[1]),
"code": line[4],
"country": line[6]
})
return lookup
def lookup_ip(ip):
if lookup_ip.lookup is None:
lookup_ip.lookup = read_list()
dec = ip_to_decimal(ip)
for l in lookup_ip.lookup:
over = l['from'] <= dec
under = l['to'] >= dec
if not over or not under:
continue
return l['country']
# Fuck globals, let's put our list *on*
# the function that's using it.
lookup_ip.lookup = None
@danneu
Copy link

danneu commented Jun 28, 2013

;; Load data  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defn comment?
  [[s]]
  (= \# (first (seq s))))

(def data
  (let [path "resources/ip-to-country.csv"
        lines (with-open [in-file (io/reader path)]
                (doall (csv/read-csv in-file)))]
    (remove comment? lines)))

;; Parse data ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defn line-to-country
  [[from to _ _ _ _ country]]
  {:from (Long/parseLong from)
   :to (Long/parseLong to)
   :country country})

(def countries 
  (map line-to-country data))

;; Country lookup ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defn get-country [ip]
  (let [in-country? (fn [ip {:keys [from to]}] (< from ip to))]
    (:country (first (filter (partial in-country? (ip-to-num ip) countries)))))

;; Usage ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(get-country "1.2.3.4") ;=> "Stralia"


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment