Python – pyshark: Access the original udp payload

pyshark: Access the original udp payload… here is a solution to the problem.

pyshark: Access the original udp payload

I’m new to pyshark. I’m trying to write a parser for a custom UDP packet. I’m using a FileCapture object to read packets from a file.

>>> cap = pyshark. FileCapture('sample.pcap')
>>> pkt = cap.next()
>>> pkt
<UDP/DATA Packet>
>>> pkt.data. data
'01ca00040500a4700500a22a5af20f830000b3aa000110da5af20f7c000bde1a000006390000666e000067f900000ba7000026ce000001d00000000100001726000100000000000000000000000017260500a4700500a22a608600250500a8c10500a22a6086013 10500a8c10500a22b608601200500a8cc0500a22a6086000c'
>>> dir(pkt.udp)
['DATA_LAYER', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__getstate__', '__hash__', '__init__', '__module__' , '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_all_fields', '_field_prefix', '_get_all_field_lines', _get_all_fields_with_alternates', '_get_field_or_layer_repr', '_get_field_repr', '_layer_name', '_sanitize_field_name', 'checksum', 'checksum_status' , 'dstport', 'field_names', 'get', 'get_field', 'get_field_by_showname', get_field_value', 'layer_name', 'length', 'port', 'pretty_print', raw_mode', 'srcport', 'stream']

I need a way to simply access the UDP payload of the packet. I found that the only way to access the raw packet data is pkt.data.data, but this returns the entire contents of the packet, and I’m only interested in the UDP part. Similar to pkt.udp.data. Is there a way to do this simply, or do I need to use pkt.data.data and calculate the offset for my data placement?

Solution

The only method I found to access raw packet data is pkt.data.data,

That’s right.

but this returns the entire content of the packet while I’m only interested to UDP portion.

Incorrect: The .data.data property is simply a hexadecimal string representation of the UDP payload itself.

For example, if your UDP payload is the ASCII string “hello”, you can retrieve it using the following method: bytearray.fromhex(pkt.data.data).decode().

(echo -n hello >/dev/udp/localhost/12345 is a quick way to verify this on the Linux console while performing a pyshark capture on lo:12345.) )

Related Problems and Solutions