Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I print in an f-string an IP address in its binary form from the output of inet_pton()?

The following code is supposed to take an IP from its user, convert it to the binary and print it to the screen.

#!/usr/bin/env python3

from socket import inet_aton, inet_pton, AF_INET

ip = input("IP?\n")

ip = inet_pton(AF_INET, ip) 

print(f"{ip}") 

When given 185.254.27.69 it prints
b'\xb9\xfe\x1bE' .f"{ip:08b}" does not work, perhaps because of the three dots in between the fours octets.. How could I get the binary address printed on the screen? Any resources of use?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Unless I’m missing something, I don’t see a reason to use inet_pton here. It converts to packed bytes, when you want a binary representation of the numbers (I assume):

ip = input("IP?\n")
print('.'.join(f'{int(num):08b}' for num in ip.split('.')))

For the input you supplied:

IP?
185.254.27.69
10111001.11111110.00011011.01000101
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading