设为首页 加入收藏

TOP

python3通过纯真IP数据库查询IP归属地信息(二)
2019-05-23 15:03:17 】 浏览:27
Tags:python3 通过 纯真 数据库 查询 属地 信息
R - 1: 112 M = int((L + R) / 2) 113 self._set_ip_range(M) 114 if ip == self.cur_start_ip: 115 L = M 116 break 117 if ip > self.cur_start_ip: 118 L = M 119 else: 120 R = M 121 self._set_ip_range(L) 122 # version information, 255.255.255.X, urgy but useful 123 if ip & 0xffffff00 == 0xffffff00: 124 self._set_ip_range(R) 125 if self.cur_start_ip <= ip <= self.cur_end_ip: 126 address = self._get_addr(self.cur_end_ip_offset) 127 else: 128 address = "未找到该IP的地址" 129 return address 130 131 def get_ip_range(self, ip): 132 ''' 133 返回ip所在记录的IP段 134 :param ip: ip(str or int) 135 :return: str 136 ''' 137 if type(ip) == str: 138 ip = self.str2ip(ip) 139 self.get_addr_by_ip(ip) 140 range = self.ip2str(self.cur_start_ip) + ' - ' \ 141 + self.ip2str(self.cur_end_ip) 142 return range 143 144 def get_offset_string(self, offset=0): 145 ''' 146 获取文件偏移处的字符串(以'\0'结尾) 147 :param offset: 偏移 148 :return: str 149 ''' 150 if offset: 151 self.f_db.seek(offset) 152 bs = b'' 153 ch = self.f_db.read(1) 154 (byte,) = struct.unpack('B', ch) 155 while byte != 0: 156 bs += ch 157 ch = self.f_db.read(1) 158 (byte,) = struct.unpack('B', ch) 159 return bs.decode('gbk') 160 161 def ip2str(self, ip): 162 ''' 163 整数IP转化为IP字符串 164 :param ip: 165 :return: 166 ''' 167 return str(ip >> 24) + '.' + str((ip >> 16) & 0xff) + '.' + str((ip >> 8) & 0xff) + '.' + str(ip & 0xff) 168 169 def str2ip(self, s): 170 ''' 171 IP字符串转换为整数IP 172 :param s: 173 :return: 174 ''' 175 (ip,) = struct.unpack('I', socket.inet_aton(s)) 176 return ((ip >> 24) & 0xff) | ((ip & 0xff) << 24) | ((ip >> 8) & 0xff00) | ((ip & 0xff00) << 8) 177 178 def getLong3(self, offset=0): 179 ''' 180 3字节的数值 181 :param offset: 182 :return: 183 ''' 184 if offset: 185 self.f_db.seek(offset) 186 bs = self.f_db.read(3) 187 (a, b) = struct.unpack('HB', bs) 188 return (b << 16) + a 189 190 191 192 if __name__ == '__main__': 193 cz = CzIp() 194 print(cz.get_version()) 195 ip = '14.215.177.39' 196 print(cz.get_ip_range(ip)) 197 print(cz.get_addr_by_ip(ip))

运行结果:

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇运维DBA要不要学python 下一篇Flask中的CBV

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目