#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import struct class IPToGeoException(Exception): pass class IPToGeo(object): MAGIC = 0x179E08EF VERSION = 1 REQ = 1 RESP = 0 IPV4 = 4 IPV6 = 16 IP_NOT_FOUND = 6 PACKET_SIZE = 32 ERRORS = {1 : 'Bad magic', 2 : 'Bad version', 3 : 'Bad request field' , 4 : 'Bad IP version', 5 : 'Unsupported IP version', 6 : 'IP not found'} def __init__(self, remote_addr='127.0.0.1', remote_port=53333, timeout=None): self._remote_addr = remote_addr self._remote_port = remote_port self._timeout = timeout self._create_socket() def _create_socket(self): self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not self._timeout is None: self._socket.settimeout(self._timeout) self._socket.connect((self._remote_addr, self._remote_port)) def _create_request(self, ip): packet = '' packet += struct.pack('