Question

I've been able to find packets of interest using code based on this example:

How can I filter a pcap file by specific protocol using python?

The next child from the TCP packet is the actual data:

   if isinstance(child1, TCP):
        if child1.get_th_dport() == 80:
           x = child1.child()
           print x

This prints out the packet data like wire shark and shows hex and ascii versions. However I have been unable so far to find a way to simply get the hex contents. I know I can manipulate the printable output but I figured there must be a way to get the data in the hex form...

I've looked through the samples but none seem to do this. Anybody know the right way?

Was it helpful?

Solution

You can use packet.get_data_as_string() to get the raw bytes, and then display it however you like. I've replicated the "hex column" output produced by print child. Should be easy to tweak to produce ASCII columns as well:

def display_hex(pkt, cols=8):
    size = cols * 4
    data = ''.join('%02x' % ord(b) for b in pkt.get_data_as_string())
    for i in range(0, len(data), size):
        for j in range(0, size, 4):
            print data[i+j:i+j+4],
        print

if isinstance(child, TCP):
    display_hex(child)

Output:

1703 0103 b0b1 9387 be4e fe00 9230 6192
e3bb 217e c1cb 8511 556f f986 4f31 542d
15c6 f42e f3bb 93d5 cf33 f126 c174 dbc4
... snip ...
8b1d 8707 96d6 7a18 2aab fd0b 48ee c4eb
b7d8 a67f 8bc0 597d 1044 a076 1a9e 24ba
959b fda3 1adb 2384 669c e6c8 c3b5 bef4
1189 eda8 3e  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top