某日,使用centos7,发现网络配置时,子网掩码需要手动转换;因为centos7的网络配置方式为:
nmcli connection enp4s0 modify ipv4.methord manual ipv4.address "192.168.1.120/24" ipv4.gateway "192.168.1.1" ipv4.dns "223.5.5.5"
其中没有子网掩码的配置项。于是,写一函数,实现子网掩码和位长的相互转换。
一:子网掩码转化为位长:
# coding:utf-8 def exchange_mask(mask): # 计算二进制字符串中 ‘1‘ 的个数 count_bit = lambda bin_str: len([i for i in bin_str if i==‘1‘]) # 分割字符串格式的子网掩码为四段列表 mask_splited = mask.split(‘.‘) # 转换各段子网掩码为二进制, 计算十进制 mask_count = [count_bit(bin(int(i))) for i in mask_splited] return sum(mask_count) if __name__ == ‘__main__‘: print exchange_mask(‘255.255.0.0‘)
二:位长转化为子网掩码:
#codint = utf8 def exchange_maskint(mask_int): bin_arr = [‘0‘ for i in range(32)] for i in range(mask_int): bin_arr[i] = ‘1‘ tmpmask = [‘‘.join(bin_arr[i * 8:i * 8 + 8]) for i in range(4)] tmpmask = [str(int(tmpstr, 2)) for tmpstr in tmpmask] return ‘.‘.join(tmpmask) if __name__ == ‘__main__‘: print exchange_maskint(24)
时间: 2024-10-26 20:49:29