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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad