Login

WorldIP - access to IP database over API

Author:
Alrond
Posted:
September 11, 2008
Language:
Python
Version:
1.0
Tags:
ip geolocation geodjango worldip
Score:
0 (after 0 ratings)

The WorldIP database provides real-world geographical location. Database is more correct than Whois records and Whois-based databases, that show geographic locations of network owners, and not the geographic location of Internet-connected PC or appliance itself. See more: WIPmania.com

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python
# Licensed under GPL 2.0
# worldip.py - access to WorldIP database over online-API
"""
This code shows how to get the country of users.
It uses online API of WIPmania project.

The WorldIP database provides real-world geographical location. Database is
more correct than Whois records and Whois-based databases, that show 
geographic locations of network owners, and not the geographic location of
Internet-connected PC or appliance itself. See more: http://www.wipmania.com

API-format is very simple:
 http://api.wipmania.com/[IPADDR]?[URL]

IPADDR - queried IP address. For example, your visitor's address.
URL - your domain name. It will be used to control your daily limits.

For example: Google.com is enquiring about the IP address 123.45.67.89
The query will look as follows:
 http://api.wipmania.com/123.45.67.89?google.com
As a result: a double-character country code, “KR” for South Korea.

In views add:
  from worldip import getUserCountry
  remote_addr = request.META.get('REMOTE_ADDR',"127.0.0.1")
  country = getUserCountry(remote_addr)

Add in settings.py your URL as SITE_URL, like
SITE_URL = "http://www.google.com"
"""

from urllib2 import urlopen, Request
import re, socket
from django.conf import settings

domain_re = re.compile('^(http|https):\/\/?([^\/]+)')
domain = domain_re.match(settings.SITE_URL).group(2)

def getUserCountry(ip):
    url = "http://api.wipmania.com/" + ip + "?" + domain
    socket.setdefaulttimeout(5)
    headers = {'Typ':'django','Ver':'1.0','Connection':'Close'}
    try:
        req = Request(url, None, headers)
        urlfile = urlopen(req)
        land = urlfile.read()
        urlfile.close()
        return land[:2]
    except Exception:
        return "XX"

More like this

  1. Test IP against IP address+Subnet whitelist by mtigas 5 years, 8 months ago
  2. SQL Log Middleware - with multiple databases by guglielmocelata 4 years, 1 month ago
  3. MongoDB data load by jose_lpa 2 years, 2 months ago
  4. MaxMind(R) GeoIP Lite geolocation models by jbronn 7 years, 8 months ago
  5. Dump a model instance and related objects as a Python data structure by akaihola 3 years, 1 month ago

Comments

Please login first before commenting.