当我像这样使用inet_aton()时
packed_ip_addr = socket.inet_aton(ip_addr)
并打印打包IP的值:
print "Packed IP: %s" %packed_ip_addr
屏幕上没有显示任何内容。如何打印IP地址的确切二进制格式?
答案 0 :(得分:0)
试试这个:
>>> ip = "192.168.137.39"
>>> print(bin(sum([int(k) * v for k, v in zip(ip.split("."), [1 << 24, 1 << 16, 1 << 8, 1])])))
0b11000000101010001000100100100111
答案 1 :(得分:0)
使用str.format()
和bytearray()
,您可以拥有此IP的二进制表示形式:192.168.1.2
,如下所示:
Python2和Python3:
import socket
a = socket.inet_aton("192.168.1.2")
b = bytearray(a)
# If you don't want to have '0b' at the final output:
# c = '{0:b}'.format(int(''.join(map(str, b))))
c = '0b{0:b}'.format(int(''.join(map(str, b))))
# print(c)
print c
>>> '0b1001001010011100110101100'