Using Python to convert the subnet mask address to the bit length

Source: Internet
Author: User
Tags string format

One day, using Centos7, when discovering the network configuration, the subnet mask needs to be converted manually, because the CENTOS7 network is configured as follows:

NMCLI Connection Enp4s0 Modify Ipv4.methord manual ipv4.address "192.168.1.120/24" Ipv4.gateway "192.168.1.1" Ipv4.dns "2 23.5.5.5 "

A configuration item with no subnet mask. Then, write a function that implements the mutual transformation of the subnet mask and the bit length.


One: The subnet mask is converted to bit length:

# Coding:utf-8 def exchange_mask (mask): # Calculates the number of ' 1 ' in a binary string count_bit = Lambda Bin_str:len ([I for I in Bin_str if I     = = ' 1 ']) # The subnet mask for the split string format is a four segment list mask_splited = Mask.split ('. ') # Convert each satin netmask to binary, calculate decimal 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 ')


Second: The bit length is converted to a subnet mask:

#codint = Utf8def Exchange_maskint (mask_int): Bin_arr = [' 0 ' for I in range (+)] 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 TMPM Ask] return '. '. Join (tmpmask) if __name__ = = ' __main__ ': Print Exchange_maskint (24)


This article is from the "Black Time" blog, so be sure to keep this source http://blacktime.blog.51cto.com/11722918/1875549

Using Python to convert the subnet mask address to the bit length

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.