Ad

How Can I Print In An F-string An IP Address In The Dotted Binary Notation 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 dotted binary format of an IP printed on the screen? Any resources of use?

Ad

Answer

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
Ad
source: stackoverflow.com
Ad