Created
June 17, 2026 13:00
-
-
Save LukasWoodtli/351ed51d5ffd58ef683a94b6b3fbb4c1 to your computer and use it in GitHub Desktop.
Get CoAP messages from pcap files and create test messages for Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| from pathlib import Path | |
| import sys | |
| import aiocoap | |
| from aiocoap.optiontypes import StringOption | |
| from scapy.contrib.coap import CoAP | |
| from scapy.layers.inet import UDP | |
| from scapy.utils import PcapReader | |
| SCRIPT_DIR = Path(__file__).parent | |
| def main(pcap_file: Path): | |
| a = PcapReader(str(pcap_file)) | |
| code = "import aiocoap" | |
| a = [p for p in a if UDP in p and p.haslayer(CoAP)] | |
| for i, pkt in enumerate(a): | |
| c = pkt.getlayer(CoAP) | |
| code += f"\n# src: {pkt.src} dst: {pkt.dst}\n" | |
| aiocoap_msg = aiocoap.message.Message.decode(c.original) | |
| code += ( | |
| f"msg_{i} = aiocoap.message.Message(" | |
| f"mtype=aiocoap.message.Type.{aiocoap.numbers.types.Type(aiocoap_msg.mtype).name}, " | |
| f"code=aiocoap.message.Code.{aiocoap_msg.code.name}, payload={aiocoap_msg.payload})\n" | |
| ) | |
| for j, opt in enumerate(aiocoap_msg.opt.option_list()): | |
| if type(opt) is StringOption: | |
| val = f'"{opt.value}"' | |
| else: | |
| val = opt.value | |
| code += ( | |
| f"msg_{i}.opt.add_option(" | |
| f"aiocoap.numbers.optionnumbers.OptionNumber.{opt.number.name}.create_option(value={val}))\n" | |
| ) | |
| with open(SCRIPT_DIR / "coap_test_msgs.py", "w") as f: | |
| f.write(code) | |
| if __name__ == "__main__": | |
| path = Path(sys.argv[1]) | |
| main(path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment