internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: secdev/scapy

Issue:
Python 3: specifying a network as ARP.pdst breaks .show()
Hello, I have a problem with the .show() method on the ARP() function when using a CIDR notation for the pdst attribute.

```
>>> ARP(pds="172.63.11.16/16").show()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/scapy/packet.py", line 1047, in show
    return self._show_or_dump(dump, indent, lvl, label_lvl)
  File "/usr/lib/python3.6/site-packages/scapy/packet.py", line 1021, in _show_or_dump
    reprval = f.i2repr(self,fvalue)
  File "/usr/lib/python3.6/site-packages/scapy/fields.py", line 221, in i2repr
    x = self.i2h(pkt, x)
  File "/usr/lib/python3.6/site-packages/scapy/layers/l2.py", line 120, in i2h
    iff = self.getif(pkt)
  File "/usr/lib/python3.6/site-packages/scapy/layers/l2.py", line 139, in <lambda>
    getif=lambda pkt: pkt.route()[0],
  File "/usr/lib/python3.6/site-packages/scapy/layers/l2.py", line 302, in route
    dst = iter(dst).next()
AttributeError: 'generator' object has no attribute 'next'
```

Kernel: 4.13.11-1-ARCH
OS: Arch Linux x64
Python version: 3.6.3
Scapy version: Version 2.3.3.dev894 (from the git)

Thanks.


Discussion:

Resolving patch:
diff --git a/scapy/layers/l2.py b/scapy/layers/l2.py
--- a/scapy/layers/l2.py
+++ b/scapy/layers/l2.py
@@ -60,7 +60,7 @@ def __repr__(self):
 def getmacbyip(ip, chainCC=0):
     """Return MAC address corresponding to a given IP address"""
     if isinstance(ip, Net):
-        ip = iter(ip).next()
+        ip = next(iter(ip))
     ip = inet_ntoa(inet_aton(ip))
     tmp = [orb(e) for e in inet_aton(ip)]
     if (tmp[0] & 0xf0) == 0xe0: # mcast @
@@ -299,7 +299,7 @@ def answers(self, other):
     def route(self):
         dst = self.pdst
         if isinstance(dst,Gen):
-            dst = iter(dst).next()
+            dst = next(iter(dst))
         return conf.route.route(dst)
     def extract_padding(self, s):
         return "",s
diff --git a/scapy/volatile.py b/scapy/volatile.py
--- a/scapy/volatile.py
+++ b/scapy/volatile.py
@@ -151,7 +151,7 @@ class RandEnum(RandNum):
     def __init__(self, min, max, seed=None):
         self.seq = RandomEnumeration(min,max,seed)
     def _fix(self):
-        return self.seq.next()
+        return next(self.seq)
 
 class RandByte(RandNum):
     def __init__(self):
@@ -224,7 +224,7 @@ def __init__(self, enum, seed=None):
         self.seq = RandomEnumeration(0, len(self.enum) - 1, seed)
 
     def _fix(self):
-        return self.enum[self.seq.next()]
+        return self.enum[next(self.seq)]
 
 class RandChoice(RandField):
     def __init__(self, *args):


Test patch:
Repository: secdev/scapy

Issue:
[ci] Import error with Travis on osx
Issue found will investigating and fixing #827  .

In this build https://travis-ci.org/secdev/scapy/jobs/320169025, it looks like Scapy is not configured correctly. The output of `python -c "from scapy.all import *; print conf"` is:
```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "scapy/all.py", line 25, in <module>
    from scapy.route import *
  File "scapy/route.py", line 14, in <module>
    from scapy.arch import get_working_if
ImportError: cannot import name get_working_if
```


Discussion:
can you give more info? what system do you use? 
This commit was merged `abe5cc9`, so i tried to checkout and install scapy, i have ubuntu and i dont have your problem.
I wrote and merged the commit that your are referring =)

As the title states, it is an OS X issue related to Travis. I guess that it can be reproduced with
`SCAPY_USE_PCAPDNET=yes python -c "from scapy.all import *; print conf"`
yes, it does :(
```
 /m/d/g/scapy> export SCAPY_USE_PCAPDNET=yes
 /m/d/g/scapy> python -c "from scapy.all import *; print conf"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "scapy/all.py", line 16, in <module>
    from scapy.arch import *
  File "scapy/arch/__init__.py", line 54, in <module>
    from scapy.arch.pcapdnet import *
  File "scapy/arch/pcapdnet.py", line 350, in <module>
    import pcapy as pcap
ImportError: No module named pcapy
```


Resolving patch:
diff --git a/scapy/arch/pcapdnet.py b/scapy/arch/pcapdnet.py
--- a/scapy/arch/pcapdnet.py
+++ b/scapy/arch/pcapdnet.py
@@ -557,6 +557,19 @@ def get_if_list():
             return [i.get("name", None) for i in dnet.intf()]
 
 
+        def get_working_if():
+            """Returns the first interface than can be used with dnet"""
+
+            if_iter = iter(dnet.intf())
+
+            try:
+                intf = next(if_iter)
+            except StopIteration:
+                return scapy.consts.LOOPBACK_NAME
+
+            return intf.get("name", scapy.consts.LOOPBACK_NAME)
+
+
 if conf.use_pcap and conf.use_dnet:
     class L3dnetSocket(SuperSocket):
         desc = "read/write packets at layer 3 using libdnet and libpcap"


Test patch:
Repository: secdev/scapy

Issue:
BERcodec_STRING With RandString cause length incorrect
Scapy Version: 2.3.3.dev929
System: OSX 10.13.1
Python Version: 2.7.13

Using RandString with ASN1_STRING will cause length enc incorrect.
This code can reappear that problem.

```python
from scapy.all import *

for i in range(10):
    data = str(ASN1_STRING(RandString()))
    enc_len = ord(data[1])
    str_len = len(data[2:])
    if enc_len != str_len:
        print("Got enc length incorrect, enc_length:%s, data_length:%s" % (enc_len, str_len))
        print("Hex string is: %s" % data[2:].encode('hex'))
```

When BERcodec_STRING input should be string but got RandString instance. 
len(s) and raw(s) in BERcodec_STRING will trigger RandString._fix() twice and got two different string.

A simple fix may look like this.
```python
class BERcodec_STRING(BERcodec_Object):
    tag = ASN1_Class_UNIVERSAL.STRING
    @classmethod
    def enc(cls,s):
        s=str(s)
        return chb(hash(cls.tag))+BER_len_enc(len(s))+raw(s) # Be sure we are encoding bytes
```


Discussion:

Resolving patch:
diff --git a/scapy/asn1/ber.py b/scapy/asn1/ber.py
--- a/scapy/asn1/ber.py
+++ b/scapy/asn1/ber.py
@@ -337,7 +337,8 @@ class BERcodec_STRING(BERcodec_Object):
     tag = ASN1_Class_UNIVERSAL.STRING
     @classmethod
     def enc(cls,s):
-        return chb(hash(cls.tag))+BER_len_enc(len(s))+raw(s) # Be sure we are encoding bytes
+        s = raw(s)
+        return chb(hash(cls.tag))+BER_len_enc(len(s))+s  # Be sure we are encoding bytes
     @classmethod
     def do_dec(cls, s, context=None, safe=False):
         l,s,t = cls.check_type_check_len(s)


Test patch:
Repository: secdev/scapy

Issue:
Problems while importing scapy on some environments (e.g. Eclipse, some peculiarly configured Windows boxes etc.) 
Scapy Version: v2.3.3-1008
System: Windows10
Python Version: 2.7.14

Updated (closed) issue: [#1029](https://github.com/secdev/scapy/issues/1029l)

File: scapy/\_\_init\_\_.py

There are a problems of using master/scapy  on some environments  like e.g. Eclipse, some peculiarly configured Windows - mostly old - boxes etc.)
When scapy is started/imported and git is installed, some console windows appears while _version() is performed.
Also this issue has impact on decrease of scapy launch/import speed.

Problem (unexpected lauching of git, git bash console window appearing) exist because of
condition in _version_from_git_describe() does not works as expected on my/our boxes (old Windows?, old buggy Python 2.7.8 where '/' path separator is not treated in the same way as '\\'? nevermind...)

Simple fix below fully avoids our problems:

```
diff --git a/scapy/__init__.py b/scapy/__init__.py
index 4893a9f..4f38578 100644
--- a/scapy/__init__.py
+++ b/scapy/__init__.py
@@ -38,7 +38,7 @@ def _version_from_git_describe():
         >>> _version_from_git_describe()
         '2.3.2.dev346'
     """
-    if not os.path.isdir(os.path.join(_SCAPY_PKG_DIR, '../.git')):
+    if not os.path.isdir(os.path.join(os.path.dirname(_SCAPY_PKG_DIR), '.git')):
         raise ValueError('not in scapy git repo')
 
     p = subprocess.Popen(['git', 'describe', '--always'], cwd=_SCAPY_PKG_DIR,
```

Thanks,
Adam Karpierz



Discussion:

Resolving patch:
diff --git a/scapy/__init__.py b/scapy/__init__.py
--- a/scapy/__init__.py
+++ b/scapy/__init__.py
@@ -38,7 +38,7 @@ def _version_from_git_describe():
         >>> _version_from_git_describe()
         '2.3.2.dev346'
     """
-    if not os.path.isdir(os.path.join(_SCAPY_PKG_DIR, '../.git')):
+    if not os.path.isdir(os.path.join(os.path.dirname(_SCAPY_PKG_DIR), '.git')):
         raise ValueError('not in scapy git repo')
 
     p = subprocess.Popen(['git', 'describe', '--always'], cwd=_SCAPY_PKG_DIR,


Test patch:
Repository: secdev/scapy

Issue:
RDataField treats NS, CNAME as DNS string type.
That's about it. At present the code only correctly handles PTR RRs, this makes it so that it also handles NS and CNAME RRs.


Discussion:

Resolving patch:
diff --git a/scapy/layers/dns.py b/scapy/layers/dns.py
old mode 100644
new mode 100755
--- a/scapy/layers/dns.py
+++ b/scapy/layers/dns.py
@@ -194,7 +194,7 @@ def m2i(self, pkt, s):
         family = None
         if pkt.type == 1: # A
             family = socket.AF_INET
-        elif pkt.type == 12: # PTR
+        elif pkt.type in [2, 5, 12]: # NS, CNAME, PTR
             l = orb(s[0])
             if l & 0xc0 and hasattr(pkt, "_orig_s") and pkt._orig_s: # Compression detected
                 p = ((l & ~0xc0) << 8) + orb(s[1]) - 12


Test patch:
Repository: secdev/scapy

Issue:
Update notebooks
Some notebooks still use `str()`: replace these calls with `raw()`.


Discussion:
I am working on it.

Resolving patch:
diff --git a/scapy/asn1/asn1.py b/scapy/asn1/asn1.py
--- a/scapy/asn1/asn1.py
+++ b/scapy/asn1/asn1.py
@@ -325,12 +325,14 @@ def __setattr__(self, name, value):
             super(ASN1_Object, self).__setattr__(name, value)
     def __repr__(self):
         if len(self.val) <= 16:
-            return "<%s[%s] (%d unused bit%s)>" % (self.__dict__.get("name", self.__class__.__name__), self.val.decode(), self.unused_bits, "s" if self.unused_bits>1 else "")
+            v = plain_str(self.val)
+            return "<%s[%s] (%d unused bit%s)>" % (self.__dict__.get("name", self.__class__.__name__), v, self.unused_bits, "s" if self.unused_bits>1 else "")
         else:
             s = self.val_readable
             if len(s) > 20:
                 s = s[:10] + b"..." + s[-10:]
-            return "<%s[%s] (%d unused bit%s)>" % (self.__dict__.get("name", self.__class__.__name__), s.decode(), self.unused_bits, "s" if self.unused_bits>1 else "")
+            v = plain_str(self.val)
+            return "<%s[%s] (%d unused bit%s)>" % (self.__dict__.get("name", self.__class__.__name__), v, self.unused_bits, "s" if self.unused_bits>1 else "")
     def __str__(self):
         return self.val_readable
     def __bytes__(self):


Test patch:
diff --git a/test/pipetool.uts b/test/pipetool.uts
--- a/test/pipetool.uts
+++ b/test/pipetool.uts
@@ -278,8 +278,8 @@ p.wait_and_stop()
 
 results = rdpcap("t2.pcap")
 
-assert str(results[0]) == str(req)
-assert str(results[1]) == str(rpy)
+assert raw(results[0]) == raw(req)
+assert raw(results[1]) == raw(rpy)
 
 os.unlink("t.pcap")
 os.unlink("t2.pcap")
diff --git a/test/regression.uts b/test/regression.uts
--- a/test/regression.uts
+++ b/test/regression.uts
@@ -136,7 +136,7 @@ b = six.moves.cPickle.dumps(a)
 c = six.moves.cPickle.loads(b)
 
 assert c[IP].dst == "192.168.0.1"
-assert str(c) == str(a)
+assert raw(c) == raw(a)
 
 = Usage test
 
@@ -777,6 +777,10 @@ a = ASN1_BIT_STRING("test", "value")
 a
 assert raw(a) == b'test'
 
+a = ASN1_BIT_STRING(b"\xff"*16, "value")
+a
+assert raw(a) == b'\xff'*16
+
 = ASN1 - ASN1_SEQUENCE
 a = ASN1_SEQUENCE([ASN1_Object(1), ASN1_Object(0)])
 assert a.strshow() == '# ASN1_SEQUENCE:\n  <ASN1_Object[1]>\n  <ASN1_Object[0]>\n'
diff --git a/test/sslv2.uts b/test/sslv2.uts
--- a/test/sslv2.uts
+++ b/test/sslv2.uts
@@ -182,7 +182,7 @@ t2.tls_session.rcs.seq_num == 6 and t2.tls_session.wcs.seq_num == 4
 
 + Check TLS-related scapy internals
 
-= Check TLS-related scapy internals - Checking str() harmlessness (with RC4)
+= Check TLS-related scapy internals - Checking raw() harmlessness (with RC4)
 t1.show()
 assert(t1.msg[0].load == b'These are horrendous parameters for a TLS session.\n')
 assert(t1.tls_session.rcs.seq_num == 6 and t1.tls_session.wcs.seq_num == 4)
Repository: secdev/scapy

Issue:
Trifle (Windows only): unnecessary doubled .strip()
Scapy version: v2.4.0rc3-31
System: Windows10
Python Version: 2.7.14

```
diff --git a/scapy/arch/windows/__init__.py b/scapy/arch/windows/__init__.py
index 6641970..886342d 100755
--- a/scapy/arch/windows/__init__.py
+++ b/scapy/arch/windows/__init__.py
@@ -521,7 +521,7 @@ class NetworkInterface(object):
         Only available with Npcap."""
         # According to https://nmap.org/npcap/guide/npcap-devguide.html#npcap-feature-dot11
         self._check_npcap_requirement()
-        return sp.Popen([_WlanHelper, self.guid[1:-1], "channel"], stdout=sp.PIPE).communicate()[0].strip().strip()
+        return sp.Popen([_WlanHelper, self.guid[1:-1], "channel"], stdout=sp.PIPE).communicate()[0].strip()
 
     def setchannel(self, channel):
         """Set the channel of the interface (1-14):
```

Thanks,
Adam Karpierz



Discussion:

Resolving patch:
diff --git a/scapy/arch/windows/__init__.py b/scapy/arch/windows/__init__.py
--- a/scapy/arch/windows/__init__.py
+++ b/scapy/arch/windows/__init__.py
@@ -521,7 +521,8 @@ def channel(self):
         Only available with Npcap."""
         # According to https://nmap.org/npcap/guide/npcap-devguide.html#npcap-feature-dot11
         self._check_npcap_requirement()
-        return sp.Popen([_WlanHelper, self.guid[1:-1], "channel"], stdout=sp.PIPE).communicate()[0].strip().strip()
+        return sp.Popen([_WlanHelper, self.guid[1:-1], "channel"],
+                        stdout=sp.PIPE).communicate()[0].strip()
 
     def setchannel(self, channel):
         """Set the channel of the interface (1-14):


Test patch:
Repository: secdev/scapy

Issue:
DNSRR issue
I am testing newest scapy with python3 and I've found a problem with DNSRR packet:

```python
p = DNS(qr=1, qd=DNSQR(qtype='A', qname='example.com'), an=DNSRR(type='A', rdata='1.2.3.4'))
bytes(p)

```
```
Traceback (most recent call last):
  File "src/scapy/scapy/compat.py", line 96, in raw
    return bytes(x)
  File "src/scapy/scapy/packet.py", line 338, in __bytes__
    return self.build()
  File "src/scapy/scapy/packet.py", line 436, in build
    p = self.do_build()
  File "src/scapy/scapy/packet.py", line 418, in do_build
    pkt = self.self_build()
  File "src/scapy/scapy/packet.py", line 399, in self_build
    p = f.addfield(self, p, val)
  File "src/scapy/scapy/fields.py", line 80, in addfield
    return s+struct.pack(self.fmt, self.i2m(pkt,val))
  File "src/scapy/scapy/layers/dns.py", line 256, in i2m
    x = len(rdataf.i2m(pkt, pkt.rdata))
  File "src/scapy/scapy/layers/dns.py", line 227, in i2m
    s = inet_aton(s)
TypeError: inet_aton() argument 1 must be str, not bytes

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "src/scapy/scapy/packet.py", line 338, in __bytes__
    return self.build()
  File "src/scapy/scapy/packet.py", line 436, in build
    p = self.do_build()
  File "src/scapy/scapy/packet.py", line 418, in do_build
    pkt = self.self_build()
  File "src/scapy/scapy/packet.py", line 399, in self_build
    p = f.addfield(self, p, val)
  File "src/scapy/scapy/fields.py", line 408, in addfield
    return s + self.i2m(pkt, val)
  File "src/scapy/scapy/layers/dns.py", line 140, in i2m
    return raw(x)
  File "src/scapy/scapy/compat.py", line 98, in raw
    return bytes(x, encoding="utf8")
TypeError: encoding without a string argument
```


Discussion:
Confirmed.
Here is a smaller case triggering this issue:
`raw(DNSRR(type='A', rdata='1.2.3.4'))`

Resolving patch:
diff --git a/scapy/layers/dns.py b/scapy/layers/dns.py
--- a/scapy/layers/dns.py
+++ b/scapy/layers/dns.py
@@ -224,7 +224,7 @@ def m2i(self, pkt, s):
     def i2m(self, pkt, s):
         if pkt.type == 1: # A
             if s:
-                s = inet_aton(s)
+                s = inet_pton(socket.AF_INET, s)
         elif pkt.type in [2, 3, 4, 5, 12]: # NS, MD, MF, CNAME, PTR
             s = b"".join(chb(len(x)) + x for x in s.split(b'.'))
             if orb(s[-1]):


Test patch:
diff --git a/test/regression.uts b/test/regression.uts
--- a/test/regression.uts
+++ b/test/regression.uts
@@ -1079,6 +1079,7 @@ del(dns_ans2[UDP].len)
 del(dns_ans2[UDP].chksum)
 assert(b"\x03www\x06secdev\x03org\x00" in raw(dns_ans2))
 assert(DNS in IP(raw(dns_ans2)))
+assert raw(DNSRR(type='A', rdata='1.2.3.4')) == b'\x00\x00\x01\x00\x01\x00\x00\x00\x00\x00\x04\x01\x02\x03\x04'
 
 = Arping
 ~ netaccess
Repository: secdev/scapy

Issue:
Scapy 2.4rc4: Look like a scapy.packet.Packet.getlayer(self, cls, ...) does not work for 'cls' argument of string type ?.
Scapy Version: 2.4.0rc4-58
System: Windows10
Python Version: 2.7.14

Look like a scapy.packet.Packet.getlayer(self, cls, ...)  does not work for 'cls' argument of string type.
None is returned/layer not found for existing layer .
But for 'cls' of class type it works OK.
For previous scapy (2.31., 2.3.2) all works as expected for both string & class type.

E.g. for layer defined as :
```
from scapy.packet import Packet
...
class ENIP_UDP(Packet):
    name = 'Class 0/1 CIP'
    fields_desc = [LEShortField('ItemCount', 2),
    ...
```
a call:
```cip_layer = packet.getlayer('Class 0/1 CIP')```
returns None
but:
```cip_layer = packet.getlayer(scapy.ENIP_UDP)```
properly returns a layer .

Thanks,
Adam Karpierz



Discussion:

Resolving patch:
diff --git a/scapy/packet.py b/scapy/packet.py
--- a/scapy/packet.py
+++ b/scapy/packet.py
@@ -882,8 +882,9 @@ def answers(self, other):
 
     def haslayer(self, cls):
         """true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax."""
-        if self.__class__ == cls or self.__class__.__name__ == cls:
-            return 1
+        if self.__class__ == cls or cls in [self.__class__.__name__,
+                                            self._name]:
+            return True
         for f in self.packetfields:
             fvalue_gen = self.getfieldval(f.name)
             if fvalue_gen is None:
@@ -913,7 +914,8 @@ def getlayer(self, cls, nb=1, _track=None, _subclass=False, **flt):
             ccls,fld = cls.split(".",1)
         else:
             ccls,fld = cls,None
-        if cls is None or match(self.__class__, cls) or self.__class__.__name__ == ccls:
+        if cls is None or match(self.__class__, cls) \
+           or ccls in [self.__class__.__name__, self._name]:
             if all(self.getfieldval(fldname) == fldvalue
                    for fldname, fldvalue in six.iteritems(flt)):
                 if nb == 1:


Test patch:
diff --git a/test/regression.uts b/test/regression.uts
--- a/test/regression.uts
+++ b/test/regression.uts
@@ -541,6 +541,20 @@ except IndexError:
 else:
     False
 
+= getlayer / haslayer with name
+~ basic getlayer IP ICMP IPerror TCPerror
+x = IP() / ICMP() / IPerror()
+assert x.getlayer(ICMP) is not None
+assert x.getlayer(IPerror) is not None
+assert x.getlayer("IP in ICMP") is not None
+assert x.getlayer(TCPerror) is None
+assert x.getlayer("TCP in ICMP") is None
+assert x.haslayer(ICMP)
+assert x.haslayer(IPerror)
+assert x.haslayer("IP in ICMP")
+assert not x.haslayer(TCPerror)
+assert not x.haslayer("TCP in ICMP")
+
 = getlayer with a filter
 ~ getlayer IP
 pkt = IP() / IP(ttl=3) / IP()
Repository: secdev/scapy

Issue:
in6_addrtovendor issue when manufdb is None
```
>>> in6_addrtovendor("fe80::40d2:67ff:fe05:8083")
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-0a5b12ee7a02> in <module>()
----> 1 in6_addrtovendor("fe80::40d2:67ff:fe05:8083")

/home/vagrant/scapy/scapy/utils6.py in in6_addrtovendor(addr)
    254         return None
    255
--> 256     res = conf.manufdb._get_manuf(mac)
    257     if len(res) == 17 and res.count(':') != 5: # Mac address, i.e. unknown
    258         res = "UNKNOWN"

AttributeError: 'NoneType' object has no attribute '_get_manuf'
```


Discussion:

Resolving patch:
diff --git a/scapy/utils6.py b/scapy/utils6.py
--- a/scapy/utils6.py
+++ b/scapy/utils6.py
@@ -250,7 +250,7 @@ def in6_addrtovendor(addr):
     is returned on error, "UNKNOWN" if the vendor is unknown.
     """
     mac = in6_addrtomac(addr)
-    if mac is None:
+    if mac is None or conf.manufdb is None:
         return None
 
     res = conf.manufdb._get_manuf(mac)


Test patch:
Repository: secdev/scapy

Issue:
wrpcap regression

`wrpcap('/tmp/empty.pcap', [])`
should write a pcap header but the file is empty instead

scapy==2.4rc5 is wrong, scapy==2.4rc4 and below was OK




Discussion:
confirmed.
We observed the same issue.
In rc5 a writing of pcpap header has been (probably intentionally) removed from:
class RawPcapWriter.write(self, pkt):
```
@@ -13,7 +13,6 @@
                 try:
                     p = next(pkt)
                 except StopIteration:
-                    self._write_header(b"")
                     return
                 self._write_header(p)
                 self._write_packet(p)
```
but unfortunately it breaks FBC :( 

Issue caused by 82e3214279fd8bb99a2f9cc1aaec8110813a762f

Here is a piece of code that could be used as a unit test:
```
from scapy.all import *
import os
import tempfile
filename = tempfile.mktemp(suffix=".pcap")
wrpcap(filename, [])
fstat = os.stat(filename)
assert fstat.st_size != 0
os.remove(filename)
```

@p-l- could you have a look?

Resolving patch:
diff --git a/scapy/utils.py b/scapy/utils.py
--- a/scapy/utils.py
+++ b/scapy/utils.py
@@ -24,7 +24,7 @@
 
 from scapy.config import conf
 from scapy.consts import DARWIN, WINDOWS
-from scapy.data import MTU
+from scapy.data import MTU, DLT_EN10MB
 from scapy.compat import *
 from scapy.error import log_runtime, log_loading, log_interactive, Scapy_Exception, warning
 from scapy.base_classes import BasePacketList
@@ -1155,6 +1155,7 @@ def write(self, pkt):
                 try:
                     p = next(pkt)
                 except StopIteration:
+                    self._write_header(None)
                     return
                 self._write_header(p)
                 self._write_packet(p)
@@ -1208,7 +1209,7 @@ def _write_header(self, pkt):
                 self.linktype = conf.l2types[pkt.__class__]
             except KeyError:
                 warning("PcapWriter: unknown LL type for %s. Using type 1 (Ethernet)", pkt.__class__.__name__)
-                self.linktype = 1
+                self.linktype = DLT_EN10MB
         RawPcapWriter._write_header(self, pkt)
 
     def _write_packet(self, packet):


Test patch:
diff --git a/test/regression.uts b/test/regression.uts
--- a/test/regression.uts
+++ b/test/regression.uts
@@ -5880,6 +5880,15 @@ wrpcap(filename, [IP()/UDP(), IPv6()/UDP()], linktype=DLT_RAW)
 packets = rdpcap(filename)
 assert(isinstance(packets[0], IP) and isinstance(packets[1], IPv6))
 
+= Check wrpcap() with no packet
+
+import tempfile
+filename = tempfile.mktemp(suffix=".pcap")
+wrpcap(filename, [])
+fstat = os.stat(filename)
+assert fstat.st_size != 0
+os.remove(filename)
+
 ############
 ############
 + LLMNR protocol