本帖最后由 codegay 于 2018-4-27 05:14 编辑
python3代码。思路是把ip地址转成一个10进制的自然数,然后range范围。再把数字转成IP地址。
IP地址转换成数字的部分参考了 https://blog.csdn.net/zhihaoma/article/details/51841169 等相关文章。- # -*- coding: utf-8 -*-
- """
- Created on Fri Apr 27 01:45:55 2018
- @author: codegay
- python3 & 编辑器 == spyder
- """
-
-
- # 把IP地址转换为一个自然数
- def IPToN(ipaddr, sep='.'):
- ip = [int(i) for i in ipaddr.split(sep)]
- result = ip[0]*256**3 + ip[1]*256**2 + ip[2]*256 + ip[3]
- return result
-
-
- # 把一个自然数转换成IP
- def NToIP(natural, sep='.'):
- ip = int(natural)
- result = [ip >> 24, (ip & 0x00FF0000) >> 16, (ip & 0x0000FF00) >> 8, ip & 0x000000FF]
- result = sep.join(map(str, result))
- return result
-
-
- def iprange(start, end, newline=''):
- result = [NToIP(n)+newline for n in range(IPToN(start), IPToN(end)+1)]
- return result
-
- print(IPToN("58.217.200.112"))
- print(IPToN("10.0.3.193"))
-
- print(NToIP(987351152))
-
- print(iprange("192.168.1.1", "192.168.1.255"))
-
- with open("ip.txt") as f:
- lines = [r.rstrip().split(" ") for r in f.readlines()]
- for line in lines:
- with open("result.txt", "w+") as rf:
- rf.writelines(iprange(line[0], line[1], newline='\r\n'))
复制代码
|