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