Reputation: 3
I want to learn packet decoder processing using dpkt. On the site, I saw the following example code:
>>> from dpkt.ip import IP
>>> ip = IP(src='\x01\x02\x03\x04', dst='\x05\x06\x07\x08', p=1)
>>> ...
How do I convert an IP String like '1.2.3.4'
to '\x01\x02\x03\x04'
?
Upvotes: 0
Views: 2628
Reputation: 369054
Use socket.inet_aton
:
>>> import socket
>>> socket.inet_aton('1.2.3.4')
'\x01\x02\x03\x04'
To get the dotted decimal back, use socket.inet_ntoa
:
>>> socket.inet_ntoa('\x01\x02\x03\x04')
'1.2.3.4'
UPDATE
In Python 3.3+, ipaddress.IPv4Address
is another option.
>>> import ipaddress
>>> ipaddress.IPv4Address('1.2.3.4').packed
b'\x01\x02\x03\x04'
>>> ipaddress.IPv4Address(b'\x01\x02\x03\x04')
IPv4Address('1.2.3.4')
>>> str(ipaddress.IPv4Address(b'\x01\x02\x03\x04'))
'1.2.3.4'
Upvotes: 5