python子网拆分IP段

# author: 阿辉枫情
import re
import struct
import socket def IPSplitBlocks(minip, maxip):
result = []
JudgeIp = re.compile(r'^(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$')
Flage_min = JudgeIp.match(minip)
Flage_max = JudgeIp.match(maxip)
if Flage_min and Flage_max:
minip_num = socket.ntohl(struct.unpack(
"I", socket.inet_aton(str(minip)))[0])
maxip_num = socket.ntohl(struct.unpack(
"I", socket.inet_aton(str(maxip)))[0])
if minip_num > maxip_num:
print "Error:[%s,%s] IP address size is not legitimate" % (minip, maxip)
exit()
else:
step = 2**(32 - subnet) - 1
min_num = minip_num
while True:
max_num = min_num & (~step & 0xFFFFFFFF)
max_num |= step & 0xFFFFFFFF
if max_num >= maxip_num:
minip = socket.inet_ntoa(
struct.pack('I', socket.htonl(min_num)))
maxip = socket.inet_ntoa(
struct.pack('I', socket.htonl(maxip_num)))
result.append((minip, maxip))
break
minip = socket.inet_ntoa(
struct.pack('I', socket.htonl(min_num)))
maxip = socket.inet_ntoa(
struct.pack('I', socket.htonl(max_num)))
result.append((minip, maxip))
min_num = max_num + 1
else:
print "Error:[%s,%s] IP addresses are not legitimate!!!" % (minip, maxip)
exit()
return result
if __name__ == '__main__':
subnet = 24
print IPSplitBlocks("192.168.1.1","192.168.2.1",)
上一篇:java基础知识回顾之java Thread类学习(十)--线程的状态以及转化使用的方法介绍


下一篇:SG 函数初步 HDU 1536 && HDU 1944