This post will describe the exercises and solutions for week two of Kirk Byers Python for Network Engineers.
The second exercise of week two is the following:
II. Create an IP address converter (dotted decimal to binary): A. Prompt a user for an IP address in dotted decimal format. B. Convert this IP address to binary and display the binary result on the screen (a binary string for each octet). Example output: first_octet second_octet third_octet fourth_octet 0b1010 0b1011000 0b1010 0b10011
We already have the knowledge to achieve this and the previous post went through all of the concepts needed to finish this task so I won’t bee too verbose with the code here.
The first part is to ask the user for an IP address using the “input()” function.
ip_add = input("\n\nPlease enter an IP address: ")
The next step is to split the IP address into octets using “split()”.
octets = ip_add.split(".")
After that each octet is converted into binary with the following code:
first_octet_bin = bin(int(octets[0])) second_octet_bin = bin(int(octets[1])) third_octet_bin = bin(int(octets[2])) fourth_octet_bin = bin(int(octets[3]))
Like in the previous post we have to convert the strings to integers before we can use “bin()” on them. We use list slicing to access the right string in the list.
Then all that is left is to print some pretty tables and reference our variables. We will use left aligned text and set the width to 20 characters.
print("\n\n") print("{:<20} {:<20} {:<20} {:<20}".format("first_octet", "second_octet", "third_octet", "fourth_octet")) print("{:<20} {:<20} {:<20} {:<20}".format(first_octet_bin, second_octet_bin, third_octet_bin, fourth_octet_bin))
We then test to run the code:
daniel@daniel-iperf3:~/python/Week2$ python3 ip_add_converter.py Please enter an IP address: 192.168.1.1 first_octet second_octet third_octet fourth_octet 0b11000000 0b10101000 0b1 0b1
Mission accomplished! Code is available at Github.