import math def bin_to_ip(bin_str): if len(bin_str) < 32: bin_str ='%s%s'%('0' * (32 - len(bin_str)), bin_str) a = bin_str[0:8] b = bin_str[8:16] c = bin_str[16:24] d = bin_str[24:32] return '%s.%s.%s.%s' % (str(int('0b%s' % a, 2)), str(int('0b%s' % b, 2)), str(int('0b%s' % c, 2)), str(int('0b%s' % d, 2))) # 二进制并计算 def bin_and(bin_str, mask_str): new_str = '' for i in range(32): if mask_str[i] == '1' and bin_str[i] == '1': new_str = "%s%s"%(new_str, 1) else: new_str = "%s%s"%(new_str, 0) return new_str # 十进制转换成二进制字符 def str_to_bin(ip, mask): ip_bin_str = '' for s in str(ip).split('.'): b_str = '' for i in range(8): try: b_str = '%s%s' % (b_str, (bin(int(s))[2:][i])) except: b_str = '%s%s' % ('0', b_str) ip_bin_str = '%s%s' % (ip_bin_str, b_str) mask_bin_str = '1' * int(mask) if len(mask_bin_str) < 32: mask_bin_str = mask_bin_str + '0' * (32 - int(mask)) return ip_bin_str, mask_bin_str def main(ip_mask): ip_str, mask_str = ip_mask.split('/') ip_bin_str, mask_bin_str = str_to_bin(ip_str, mask_str) host_ip_bin = (bin_and(ip_bin_str, mask_bin_str)) ip_num = (int(math.pow(2, 32 - int(mask_str)))) - 2 mask = bin_to_ip(mask_bin_str) host_ip = bin_to_ip(host_ip_bin) ip_list = [] for i in range(ip_num+2): ip_list.append(bin_to_ip(str(bin(int('0b%s' % host_ip_bin, 2) + i))[2:])) first_use_ip = ip_list[1] last_use_ip = ip_list[-2] broad_ip = ip_list[-1] use_ips = ip_list[1:-1] return ip_num, mask, host_ip, first_use_ip, last_use_ip, broad_ip, use_ips if __name__ == '__main__': ip_mask = '192.168.32.125/29' ip_num, mask, host_ip, first_use_ip, last_use_ip, broad_ip, use_ips = main(ip_mask) print('-+-'*8) print('ip num:', ip_num) print('mask', mask) print('host ip:', host_ip) print('first use ip:', first_use_ip) print('last use ip:', last_use_ip) print('broad ip:', broad_ip)