kbandla / dpkt

fast, simple packet creation / parsing, with definitions for the basic TCP/IP protocols
Other
1.09k stars 270 forks source link

Pretty print #574

Closed obormot closed 3 years ago

obormot commented 3 years ago

So I wanted to add this for a while. It adds a pretty-printing function to the base Packet class. Calling pkt.pprint() on a parsed packet will output

..view of the protocol fields. If a pretty-print callable is given for a field, it gets appended as a # comment after.

Example 1 - IPv6/TCP source frame

>> _ip
IP6(plen=40, nxt=6, hlim=64, src=b'\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x11$\xff\xfe\x8c\x11\xde', dst=b'\xfe\x80\x00\x00\x00\x00\x00\x00\x02\xb0\xd0\xff\xfe\xe1\x80r', extension_hdrs={}, all_extension_headers=[], p=6, data=TCP(sport=52682, dport=22, seq=75777749, off=10, flags=2, sum=63497, opts=b'\x02\x04\x05\xa0\x01\x03\x03\x00\x01\x01\x08\n}\x185?\x00\x00\x00\x00'))

Pretty-print: IPv6 addresses and TCP flags are human readable, checksum is presented in hex; protocol layers are indented and outdented at the end.

>> _ip.pprint()
IP6(
  v=6,
  fc=0,
  flow=0,
  plen=40,
  nxt=6,
  hlim=64,
  src=b'\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x11$\xff\xfe\x8c\x11\xde',  # fe80::211:24ff:fe8c:11de
  dst=b'\xfe\x80\x00\x00\x00\x00\x00\x00\x02\xb0\xd0\xff\xfe\xe1\x80r',  # fe80::2b0:d0ff:fee1:8072
  extension_hdrs={},
  all_extension_headers=[],
  p=6,
  data=TCP(
    sport=52682,
    dport=22,
    seq=75777749,
    ack=0,
    off=10,
    flags=2,  # SYN
    win=65535,
    sum=63497,  # 0xf809
    urp=0,
    opts=b'\x02\x04\x05\xa0\x01\x03\x03\x00\x01\x01\x08\n}\x185?\x00\x00\x00\x00',
  )  # TCP
)  # IP6

Example 2 - Ethernet/IP/TCP frame. MAC addresses and IP addresses are easy to read, 3 layers of indentation

Ethernet(
  dst=b'\x00\x00\x01\x00\x00\x00',  # 00:00:01:00:00:00
  src=b'\xfe\xff \x00\x01\x00',  # fe:ff:20:00:01:00
  type=2048,
  data=IP(
    v=4,
    hl=5,
    tos=0,
    len=40,
    id=0,
    off=16384,
    ttl=47,
    p=6,
    sum=62004,  # 0xf234
    src=b'A\xd0\xe4\xdf',  # 65.208.228.223
    dst=b'\x91\xfe\xa0\xed',  # 145.254.160.237
    opts=b'',
    data=TCP(
      sport=80,
      dport=3372,
      seq=290236745,
      ack=951058420,
      off=5,
      flags=16,  # ACK
      win=6432,
      sum=15459,  # 0x3c63
      urp=0,
      opts=b'',
    )  # TCP
  )  # IP
)  # Ethernet
coveralls commented 3 years ago

Coverage Status

Coverage increased (+0.001%) to 99.815% when pulling 6d87f3ac5fadd798fa234aa1d78952ebce723477 on pretty-print into 501637d8a667708b544e68c5acbd76dacc291c0d on master.