0

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?

John Smith
  • 835
  • 1
  • 7
  • 19

2 Answers2

3

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
Adid
  • 1,504
  • 3
  • 13
1

this code works for binary ip and keeps leading zeros:

from socket import inet_aton, inet_pton, AF_INET

ip = ip2 = input("IP?\n")

ip = inet_pton(AF_INET, ip)
ip2 = ip2.split(".")
ip3 = ""
for ip in ip2:
    ip = int(ip)
    if len(ip3) == 0:
        zeros = str(bin(ip)[2:]).zfill(8)
        ip3 += zeros
    else:
        zeros = str(bin(ip)[2:]).zfill(8)
        ip3 += "." + zeros
print(f"{ip3}")
Feras Alfrih
  • 492
  • 3
  • 11
  • It prints the IP in the original format - the same as given. Whereas when I give an address as `185.254.27.69` I want to receive something like `10111001.11111110.11011.1000101` – John Smith Jan 02 '22 at 12:39
  • sorry, I misunderstood your request, Answer Updated – Feras Alfrih Jan 02 '22 at 12:47
  • The problem with your code is that it does not print leading zeros, e.g. it outputs `10111001.11111110.11011.1000101` instead of `10111001.11111110.00011011.1000101` – John Smith Jan 02 '22 at 16:31
  • it is exactly as you requested, plz check your first comment – Feras Alfrih Jan 02 '22 at 16:41