]>
Commit | Line | Data |
---|---|---|
940227cb MT |
1 | #!/usr/bin/python |
2 | ||
3 | from databases import Databases | |
4 | from misc import Singleton | |
5 | ||
6 | class GeoIP(object): | |
7 | __metaclass__ = Singleton | |
8 | ||
9 | @property | |
10 | def db(self): | |
11 | return Databases().geoip | |
12 | ||
13 | def __encode_ip(self, addr): | |
14 | # ip is calculated as described in http://ipinfodb.com/ip_database.php | |
15 | a1, a2, a3, a4 = addr.split(".") | |
16 | ||
17 | return int(((int(a1) * 256 + int(a2)) * 256 + int(a3)) * 256 + int(a4) + 100) | |
18 | ||
19 | def get_country(self, addr): | |
20 | return self.db.get("SELECT * FROM ip_group_country WHERE ip_start <= %s \ | |
21 | ORDER BY ip_start DESC LIMIT 1;", self.__encode_ip(addr)).country_code.lower() | |
22 | ||
23 | def get_all(self, addr): | |
24 | # XXX should be done with a join | |
25 | location = self.db.get("SELECT location FROM ip_group_city WHERE ip_start <= %s \ | |
26 | ORDER BY ip_start DESC LIMIT 1;", self.__encode_ip(addr)).location | |
27 | ||
28 | return self.db.get("SELECT * FROM locations WHERE id = %s", int(location)) | |
29 | ||
30 | ||
31 | if __name__ == "__main__": | |
32 | g = GeoIP() | |
33 | ||
34 | print g.get_country("123.123.123.123") | |
35 | print g.get_all("123.123.123.123") |