2017-06-08 2 views
2

Lorsque j'utilise inet_aton() comme celui-cireprésentation binaire d'un IP avec inet_aton()

packed_ip_addr = socket.inet_aton(ip_addr) 

et imprimer la valeur de la propriété intellectuelle tassée:

print "Packed IP: %s" %packed_ip_addr 

Rien indiqué dans l'écran. Comment puis-je imprimer le format binaire exact de l'adresse IP?

+0

'socket.inet_aton ('127.0.0.1')' retournera un 'bytes'. Que voulez-vous dire par rien montré à l'écran? –

Répondre

0

En utilisant str.format() et bytearray(), vous pouvez avoir la représentation binaire de cette adresse IP: 192.168.1.2 comme ci-dessous:

deux python2 et 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' 
0

Essayez ceci:

>>> 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