【python】将指定的ip段,拆分为指定子网掩码的网络地址
python语言实现-拆分IP
def calculateIpSubNetAndStore(self, task): ipStart = task[0].strip() ipEnd = task[1].strip() ipStartSList = ipStart.split(".") ipEndSList = ipEnd.split(".") subMask = IpAddrConvertAndStoreThread.calculateSubMask(ipStart, ipEnd) if ipStartSList[3] != "0" and ipEndSList[3] != '255' and subMask >= 24: ipStartSList.pop() ipNet = ".".join(ipStartSList) ipNet = ipNet + str(".0") saveIpaddrCustom(self._dbLimit, self._sqlEngine, ipNet, task) return startIp = ipaddress.ip_address(ipStart) endIp = ipaddress.ip_address(ipEnd) startSubnet = IpAddrConvertAndStoreThread.calculateStartSubnet(ipStart, subMask) netWork = ipaddress.ip_network(startSubnet + "/" + str(subMask), strict=False) maskGt24Flag = subMask == 24 haveHitSubNet = False fistHitSubNet = None for r in netWork.subnets(new_prefix=24): rdata = r.network_address if maskGt24Flag and fistHitSubNet is None: # 取第一个网段作为当前记录的网络地址 fistHitSubNet = r if rdata >= startIp and rdata <= endIp: haveHitSubNet = True saveIpaddrCustom(self._dbLimit, self._sqlEngine, r.network_address, task) continue if maskGt24Flag and haveHitSubNet is False: # 大于24位子网掩码,且在迭代中未命中的,则按第一个子网作为该记录的子网 saveIpaddrCustom(self._dbLimit, self._sqlEngine, fistHitSubNet.network_address, task) if rdata > endIp: break
# 计算开始迭代的超网子网掩码 @staticmethod def calculateSubMask(ipStart: str, ipEnd: str) -> int: maskC = 0 ipSList = ipStart.split(".") ipEList = ipEnd.split(".") for i in range(len(ipSList)): if ipSList[i] == ipEList[i]: maskC += 1 else: break return maskC * 8 # 基于子网掩码和开始地址计算超网地址 @staticmethod def calculateStartSubnet(ipStart: str, mask: int) -> str: compareData = mask / 8 ipSList = ipStart.split(".") newSubNetStr = str() for i in range(len(ipSList)): newSubNetStr += "." if i < compareData: newSubNetStr += str(int(ipSList[i]) & 255) else: newSubNetStr += str(int(ipSList[i]) & 0) return newSubNetStr[1:]