| 12 | |
| 13 | |
| 14 | class IPAddresss: |
| 15 | def __init__(self, ipdbFile): |
| 16 | self.ipdb = open(ipdbFile, "rb") |
| 17 | str = self.ipdb.read(8) |
| 18 | (self.firstIndex, self.lastIndex) = struct.unpack('II', str) |
| 19 | self.indexCount = int((self.lastIndex - self.firstIndex) / 7 + 1) |
| 20 | # print self.getVersion(), u" 纪录总数: %d 条 "%(self.indexCount) |
| 21 | |
| 22 | def getVersion(self): |
| 23 | s = self.getIpAddr(0xffffff00) |
| 24 | return s |
| 25 | |
| 26 | def getAreaAddr(self, offset=0): |
| 27 | if offset: |
| 28 | self.ipdb.seek(offset) |
| 29 | str = self.ipdb.read(1) |
| 30 | (byte,) = struct.unpack('B', str) |
| 31 | if byte == 0x01 or byte == 0x02: |
| 32 | p = self.getLong3() |
| 33 | if p: |
| 34 | return self.getString(p) |
| 35 | else: |
| 36 | return "" |
| 37 | else: |
| 38 | self.ipdb.seek(-1, 1) |
| 39 | return self.getString(offset) |
| 40 | |
| 41 | def getAddr(self, offset, ip=0): |
| 42 | self.ipdb.seek(offset + 4) |
| 43 | countryAddr = "" |
| 44 | areaAddr = "" |
| 45 | str = self.ipdb.read(1) |
| 46 | (byte,) = struct.unpack('B', str) |
| 47 | if byte == 0x01: |
| 48 | countryOffset = self.getLong3() |
| 49 | self.ipdb.seek(countryOffset) |
| 50 | str = self.ipdb.read(1) |
| 51 | (b,) = struct.unpack('B', str) |
| 52 | if b == 0x02: |
| 53 | countryAddr = self.getString(self.getLong3()) |
| 54 | self.ipdb.seek(countryOffset + 4) |
| 55 | else: |
| 56 | countryAddr = self.getString(countryOffset) |
| 57 | areaAddr = self.getAreaAddr() |
| 58 | elif byte == 0x02: |
| 59 | countryAddr = self.getString(self.getLong3()) |
| 60 | areaAddr = self.getAreaAddr(offset + 8) |
| 61 | else: |
| 62 | countryAddr = self.getString(offset + 4) |
| 63 | areaAddr = self.getAreaAddr() |
| 64 | return countryAddr + " " + areaAddr |
| 65 | |
| 66 | def dump(self, first, last): |
| 67 | if last > self.indexCount: |
| 68 | last = self.indexCount |
| 69 | for index in range(first, last): |
| 70 | offset = self.firstIndex + index * 7 |
| 71 | self.ipdb.seek(offset) |