获取最新的IP分配信息
1,每天从APNIC下载
http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest
2,然后用如下代码:
with open('delegated-apnic-latest') as f:
data = f.read()
for line in filter(lambda x: x.startswith('apnic|CN|ipv4'), data.splitlines()):
item = line.split('|')
print('{}/{}'.format(item[3], 33 - int(item[4]).bit_length()))
可以得到如下格式的IP段信息:
218.104.0.0/17
3,转换成IP范围格式:
import ipaddress
ip = ipaddress.IPv4Network('223.255.0.0/17')
start_ip = ip.network_address
end_ip = ip.broadcast_address
print(f"IP Range: {start_ip} - {end_ip}")
或者:
ip = '223.255.0.0/17'
# 将IP地址和掩码分开
ip_addr, mask_len = ip.split('/')
mask_len = int(mask_len)
# 将IP地址转换为32位二进制字符串
ip_bin = ''.join([bin(int(x)).lstrip('0b').rjust(8, '0') for x in ip_addr.split('.')])
# 获取网络地址和广播地址
net_addr_bin = ip_bin[:mask_len] + '0' * (32 - mask_len)
bcast_addr_bin = ip_bin[:mask_len] + '1' * (32 - mask_len)
net_addr = '.'.join([str(int(net_addr_bin[i:i+8], 2)) for i in range(0, 32, 8)])
bcast_addr = '.'.join([str(int(bcast_addr_bin[i:i+8], 2)) for i in range(0, 32, 8)])
print("IP Range: {} - {}".format(net_addr, bcast_addr))