Reputation: 51
I want to learn packet decoder processing using dpkt. On the site, I saw the following example code:
>>> from dpkt.ip import IP
>>> from dpkt.icmp import ICMP
>>> ip = IP(src='\x01\x02\x03\x04', dst='\x05\x06\x07\x08', p=1)
>>> ip.v4
>>> ip.src
'\x01\x02\x03\x04'
>>> ip.data
''
>>>
>>> icmp = ICMP(type=8, data=ICMP.Echo(id=123, seq=1, data='foobar'))
>>> icmp
ICMP(type=8, data=Echo(id=123, seq=1, data='foobar'))
>>> len(icmp)
14
>>> ip.data = icmp
>>> ip.len += len(ip.data)
>>> ip
IP(src='\x01\x02\x03\x04', dst='\x05\x06\x07\x08', len=34, p=1, data=ICMP(type=8, data=Echo(id=123, seq=1, data='foobar')))
>>> pkt = str(ip)
>>> pkt
'E\x00\x00"\x00\x00\x00\x00@\x01j\xc8\x01\x02\x03\x04\x05\x06\x07\x08\x08\x00\xc0?\x00{\x00\x01foobar'
>>> IP(pkt)
IP(src='\x01\x02\x03\x04', dst='\x05\x06\x07\x08', sum=27336, len=34, p=1, data=ICMP(sum=49215, type=8, data=Echo(id=123, seq=1, data='foobar')))
I'm confused with lines that are using hexa such as:
ip = IP(src='\x01\x02\x03\x04', dst='\x05\x06\x07\x08', p=1)
What is the meaning of "\x01\x02\x03\x04" and "\x05\x06\x07\x08"? Is it possible to convert strings like these to something more human-readable?
Upvotes: 5
Views: 23348
Reputation: 11
"\x01\x02\x03\x04" and "\x05\x06\x07\x08" are source and destination IP addresses. You can convert them to more human-readable using socket.inet_ntoa
>>> socket.inet_ntoa('\x01\x02\x03\x04')
'1.2.3.4'
Upvotes: 1
Reputation: 40384
The values you're getting are hexadecimal string representations of the bits present in the IP headers from the packets you're working with.
Most of the times, you should be able to work with those values directly, but if you need to decode them you can use the struct module (it's nice because it will handle byte ordering for you for those fields wider than a byte) or even, in simple cases, the ord
builtin:
>>> src = '\x01\x02\x03\x04'
>>> '.'.join(str(ord(c)) for c in src)
'1.2.3.4'
Upvotes: 5
Reputation: 16037
more human readable form of '\x01\x02\x03\x04'
would be '1.2.3.4'
you can convert the parts of your string to decimal like this
>>> int('0x01', 16)
1
>>> int('0x13', 16)
19
Upvotes: 1
Reputation: 336168
In src='\x01\x02\x03\x04'
, src
is a sequence of bytes, expressed as a string. It contains the byte values 1
, 2
, 3
and 4
. These correspond to non-printable characters in the ASCII character set, which is why Python displays them using their hexadecimal escape sequences.
To get to the values as integers, you could do:
>>> [ord(c) for c in src]
[1, 2, 3, 4]
although I'm not sure that this is what you are actually looking for. Please define your problem more clearly.
Upvotes: 4