From 88052d1aa949688c481c1e22da222273d7d92eee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20V=C3=A1zquez=20Blanco?= Date: Sat, 5 Sep 2026 18:44:30 +0200 Subject: [PATCH] utils: fall back to the writer linktype for unbound layers AI-Assisted: No --- scapy/utils.py | 9 ++++++--- test/regression.uts | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/scapy/utils.py b/scapy/utils.py index bed6049fe7c..094d1c67a2b 100644 --- a/scapy/utils.py +++ b/scapy/utils.py @@ -2211,9 +2211,12 @@ def write_packet(self, ifname = getattr(packet, "sniffed_on", None) direction = getattr(packet, "direction", None) if not isinstance(packet, bytes): - linktype: int = conf.l2types.layer2num[ - packet.__class__ - ] + # The class may not be bound to any linktype (e.g. conf.raw_layer), + # in which case fall back to the one write_header() settled on. + linktype: int = conf.l2types.layer2num.get( + packet.__class__, + self.linktype, + ) else: linktype = self.linktype if ifname is not None: diff --git a/test/regression.uts b/test/regression.uts index a2e05eb8211..bc7e8f74142 100644 --- a/test/regression.uts +++ b/test/regression.uts @@ -2779,6 +2779,21 @@ with RawPcapWriter(fd) as w: w.write(b"test") assert w.linktype == 1 += Check PcapWriter with a layer that is not bound to any linktype +~ pcap + +from io import BytesIO + +f = BytesIO() +w = PcapWriter(f, linktype=DLT_RAW, sync=True) +w.write(Raw(b"test")) +assert w.linktype == DLT_RAW + +f.seek(0) or None +r = RawPcapReader(f) +assert r.linktype == DLT_RAW +assert [x for (x, y) in r] == [b"test"] + = Check tcpdump() ~ tcpdump from io import BytesIO