We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
No /dev/bpf handle is available !
I'm running on mac high sierra 10.13.4
after downloading from https://github.com/secdev/scapy/archive/v2.4.0.zip I unzipping and ran each of the following as root: 
run_scapy, run_scapy2 and run_scapy_py3
within each repl I ran:
```send(IP(dst="2.2.2.2", src="1.1.1.1"))```
and the traceback was the same:
```
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/sendrecv.py", line 302, in send
    realtime=realtime, return_packets=return_packets)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/sendrecv.py", line 276, in __gen_send
    s.send(p)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/arch/bpf/supersocket.py", line 345, in send
    frame = raw(self.guessed_cls()/pkt)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/compat.py", line 96, in raw
    return bytes(x)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/packet.py", line 345, in __bytes__
    return self.build()
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/packet.py", line 444, in build
    p = self.do_build()
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/packet.py", line 426, in do_build
    pkt = self.self_build()
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/packet.py", line 407, in self_build
    p = f.addfield(self, p, val)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/fields.py", line 80, in addfield
    return s+struct.pack(self.fmt, self.i2m(pkt,val))
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/l2.py", line 109, in i2m
    return MACField.i2m(self, pkt, self.i2h(pkt, x))
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/l2.py", line 101, in i2h
    x = conf.neighbor.resolve(pkt,pkt.payload)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/l2.py", line 49, in resolve
    return self.resolvers[k](l2inst,l3inst)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/inet.py", line 821, in inet_register_l3
    return getmacbyip(l3.dst)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/l2.py", line 84, in getmacbyip
    nofilter=1)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/sendrecv.py", line 434, in srp1
    ans, _ = srp(*args, **kargs)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/sendrecv.py", line 416, in srp
    s = conf.L2socket(promisc=promisc, iface=iface, filter=filter, nofilter=nofilter, type=type)
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/arch/bpf/supersocket.py", line 58, in __init__
    (self.ins, self.dev_bpf) = get_dev_bpf()
  File "/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/arch/bpf/core.py", line 98, in get_dev_bpf
    raise Scapy_Exception("No /dev/bpf handle is available !")
scapy.error.Scapy_Exception: No /dev/bpf handle is available !
```

after looking at some of the past issues it appears similar to this one: [#1015](https://github.com/secdev/scapy/issues/1015)
however it was solved some time ago...

Update:
The above was ran while I had wireshark running, after quitting wireshark the error stopped.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `scapy/arch/bpf/core.py`
Content:
```
1 # Guillaume Valadon <guillaume@valadon.net>
2 
3 """
4 Scapy *BSD native support - core
5 """
6 
7 from __future__ import absolute_import
8 from scapy.config import conf
9 from scapy.error import Scapy_Exception, warning
10 from scapy.data import ARPHDR_LOOPBACK, ARPHDR_ETHER
11 from scapy.arch.common import get_if, get_bpf_pointer
12 from scapy.consts import LOOPBACK_NAME
13 
14 from scapy.arch.bpf.consts import *
15 
16 import os
17 import socket
18 import fcntl
19 import struct
20 
21 from ctypes import cdll, cast, pointer, POINTER, Structure
22 from ctypes import c_int, c_ulong, c_char_p
23 from ctypes.util import find_library
24 from scapy.modules.six.moves import range
25 
26 
27 # ctypes definitions
28 
29 LIBC = cdll.LoadLibrary(find_library("libc"))
30 LIBC.ioctl.argtypes = [c_int, c_ulong, c_char_p]
31 LIBC.ioctl.restype = c_int
32 
33 
34 # Addresses manipulation functions
35 
36 def get_if_raw_addr(ifname):
37     """Returns the IPv4 address configured on 'ifname', packed with inet_pton."""
38 
39     # Get ifconfig output
40     try:
41         fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
42     except OSError as msg:
43         warning("Failed to execute ifconfig: (%s)", msg)
44         return b"\0\0\0\0"
45 
46     # Get IPv4 addresses
47     addresses = [l for l in fd if l.find("netmask") >= 0]
48     if not addresses:
49         warning("No IPv4 address found on %s !", ifname)
50         return b"\0\0\0\0"
51 
52     # Pack the first address
53     address = addresses[0].split(' ')[1]
54     return socket.inet_pton(socket.AF_INET, address)
55 
56 
57 def get_if_raw_hwaddr(ifname):
58     """Returns the packed MAC address configured on 'ifname'."""
59 
60     NULL_MAC_ADDRESS = b'\x00' * 6
61 
62     # Handle the loopback interface separately
63     if ifname == LOOPBACK_NAME:
64         return (ARPHDR_LOOPBACK, NULL_MAC_ADDRESS)
65 
66     # Get ifconfig output
67     try:
68         fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
69     except OSError as msg:
70         raise Scapy_Exception("Failed to execute ifconfig: (%s)" % msg)
71 
72     # Get MAC addresses
73     addresses = [l for l in fd.readlines() if l.find("ether") >= 0 or
74                  l.find("lladdr") >= 0 or
75                  l.find("address") >= 0]
76     if not addresses:
77         raise Scapy_Exception("No MAC address found on %s !" % ifname)
78 
79     # Pack and return the MAC address
80     mac = addresses[0].split(' ')[1]
81     mac = [chr(int(b, 16)) for b in mac.split(':')]
82     return (ARPHDR_ETHER, ''.join(mac))
83 
84 
85 # BPF specific functions
86 
87 def get_dev_bpf():
88     """Returns an opened BPF file object"""
89 
90     # Get the first available BPF handle
91     for bpf in range(0, 8):
92         try:
93             fd = os.open("/dev/bpf%i" % bpf, os.O_RDWR)
94             return (fd, bpf)
95         except OSError:
96             continue
97 
98     raise Scapy_Exception("No /dev/bpf handle is available !")
99 
100 
101 def attach_filter(fd, iface, bpf_filter_string):
102     """Attach a BPF filter to the BPF file descriptor"""
103 
104     # Retrieve the BPF byte code in decimal
105     command = "%s -i %s -ddd -s 1600 '%s'" % (conf.prog.tcpdump, iface, bpf_filter_string)
106     try:
107         f = os.popen(command)
108     except OSError as msg:
109         raise Scapy_Exception("Failed to execute tcpdump: (%s)" % msg)
110 
111     # Convert the byte code to a BPF program structure
112     lines = f.readlines()
113     if lines == []:
114         raise Scapy_Exception("Got an empty BPF filter from tcpdump !")
115 
116     bp = get_bpf_pointer(lines)
117     # Assign the BPF program to the interface
118     ret = LIBC.ioctl(c_int(fd), BIOCSETF, cast(pointer(bp), c_char_p))
119     if ret < 0:
120         raise Scapy_Exception("Can't attach the BPF filter !")
121 
122 
123 # Interface manipulation functions
124 
125 def get_if_list():
126     """Returns a list containing all network interfaces."""
127 
128     # Get ifconfig output
129     try:
130         fd = os.popen("%s -a" % conf.prog.ifconfig)
131     except OSError as msg:
132         raise Scapy_Exception("Failed to execute ifconfig: (%s)" % msg)
133 
134     # Get interfaces
135     interfaces = [line[:line.find(':')] for line in fd.readlines()
136                   if ": flags" in line.lower()]
137     return interfaces
138 
139 
140 def get_working_ifaces():
141     """
142     Returns an ordered list of interfaces that could be used with BPF.
143     Note: the order mimics pcap_findalldevs() behavior
144     """
145 
146     # Only root is allowed to perform the following ioctl() call
147     if os.getuid() != 0:
148         return []
149 
150     # Test all network interfaces
151     interfaces = []
152     for ifname in get_if_list():
153 
154         # Unlike pcap_findalldevs(), we do not care of loopback interfaces.
155         if ifname == LOOPBACK_NAME:
156             continue
157 
158         # Get interface flags
159         try:
160             result = get_if(ifname, SIOCGIFFLAGS)
161         except IOError:
162             warning("ioctl(SIOCGIFFLAGS) failed on %s !", ifname)
163             continue
164 
165         # Convert flags
166         ifflags = struct.unpack("16xH14x", result)[0]
167         if ifflags & 0x1:  # IFF_UP
168 
169             # Get a BPF handle
170             fd, _ = get_dev_bpf()
171             if fd is None:
172                 raise Scapy_Exception("No /dev/bpf are available !")
173 
174             # Check if the interface can be used
175             try:
176                 fcntl.ioctl(fd, BIOCSETIF, struct.pack("16s16x", ifname.encode()))
177                 interfaces.append((ifname, int(ifname[-1])))
178             except IOError:
179                 pass
180 
181             # Close the file descriptor
182             os.close(fd)
183 
184     # Sort to mimic pcap_findalldevs() order
185     interfaces.sort(key=lambda elt: elt[1])
186 
187     return interfaces
188 
189 
190 def get_working_if():
191     """Returns the first interface than can be used with BPF"""
192 
193     ifaces = get_working_ifaces()
194     if not ifaces:
195         # A better interface will be selected later using the routing table
196         return LOOPBACK_NAME
197     return ifaces[0][0]
198
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/scapy/arch/bpf/core.py b/scapy/arch/bpf/core.py
--- a/scapy/arch/bpf/core.py
+++ b/scapy/arch/bpf/core.py
@@ -88,7 +88,7 @@
     """Returns an opened BPF file object"""
 
     # Get the first available BPF handle
-    for bpf in range(0, 8):
+    for bpf in range(256):
         try:
             fd = os.open("/dev/bpf%i" % bpf, os.O_RDWR)
             return (fd, bpf)

{"golden_diff": "diff --git a/scapy/arch/bpf/core.py b/scapy/arch/bpf/core.py\n--- a/scapy/arch/bpf/core.py\n+++ b/scapy/arch/bpf/core.py\n@@ -88,7 +88,7 @@\n     \"\"\"Returns an opened BPF file object\"\"\"\n \n     # Get the first available BPF handle\n-    for bpf in range(0, 8):\n+    for bpf in range(256):\n         try:\n             fd = os.open(\"/dev/bpf%i\" % bpf, os.O_RDWR)\n             return (fd, bpf)\n", "issue": "No /dev/bpf handle is available !\nI'm running on mac high sierra 10.13.4\r\nafter downloading from https://github.com/secdev/scapy/archive/v2.4.0.zip I unzipping and ran each of the following as root: \r\nrun_scapy, run_scapy2 and run_scapy_py3\r\nwithin each repl I ran:\r\n```send(IP(dst=\"2.2.2.2\", src=\"1.1.1.1\"))```\r\nand the traceback was the same:\r\n```\r\nTraceback (most recent call last):\r\n  File \"<console>\", line 1, in <module>\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/sendrecv.py\", line 302, in send\r\n    realtime=realtime, return_packets=return_packets)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/sendrecv.py\", line 276, in __gen_send\r\n    s.send(p)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/arch/bpf/supersocket.py\", line 345, in send\r\n    frame = raw(self.guessed_cls()/pkt)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/compat.py\", line 96, in raw\r\n    return bytes(x)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/packet.py\", line 345, in __bytes__\r\n    return self.build()\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/packet.py\", line 444, in build\r\n    p = self.do_build()\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/packet.py\", line 426, in do_build\r\n    pkt = self.self_build()\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/packet.py\", line 407, in self_build\r\n    p = f.addfield(self, p, val)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/fields.py\", line 80, in addfield\r\n    return s+struct.pack(self.fmt, self.i2m(pkt,val))\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/l2.py\", line 109, in i2m\r\n    return MACField.i2m(self, pkt, self.i2h(pkt, x))\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/l2.py\", line 101, in i2h\r\n    x = conf.neighbor.resolve(pkt,pkt.payload)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/l2.py\", line 49, in resolve\r\n    return self.resolvers[k](l2inst,l3inst)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/inet.py\", line 821, in inet_register_l3\r\n    return getmacbyip(l3.dst)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/layers/l2.py\", line 84, in getmacbyip\r\n    nofilter=1)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/sendrecv.py\", line 434, in srp1\r\n    ans, _ = srp(*args, **kargs)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/sendrecv.py\", line 416, in srp\r\n    s = conf.L2socket(promisc=promisc, iface=iface, filter=filter, nofilter=nofilter, type=type)\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/arch/bpf/supersocket.py\", line 58, in __init__\r\n    (self.ins, self.dev_bpf) = get_dev_bpf()\r\n  File \"/Users/idobn/dev/research/something/playground/tmp/scapy-2.4.0/scapy/arch/bpf/core.py\", line 98, in get_dev_bpf\r\n    raise Scapy_Exception(\"No /dev/bpf handle is available !\")\r\nscapy.error.Scapy_Exception: No /dev/bpf handle is available !\r\n```\r\n\r\nafter looking at some of the past issues it appears similar to this one: [#1015](https://github.com/secdev/scapy/issues/1015)\r\nhowever it was solved some time ago...\r\n\r\nUpdate:\r\nThe above was ran while I had wireshark running, after quitting wireshark the error stopped.\n", "before_files": [{"content": "# Guillaume Valadon <guillaume@valadon.net>\n\n\"\"\"\nScapy *BSD native support - core\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom scapy.config import conf\nfrom scapy.error import Scapy_Exception, warning\nfrom scapy.data import ARPHDR_LOOPBACK, ARPHDR_ETHER\nfrom scapy.arch.common import get_if, get_bpf_pointer\nfrom scapy.consts import LOOPBACK_NAME\n\nfrom scapy.arch.bpf.consts import *\n\nimport os\nimport socket\nimport fcntl\nimport struct\n\nfrom ctypes import cdll, cast, pointer, POINTER, Structure\nfrom ctypes import c_int, c_ulong, c_char_p\nfrom ctypes.util import find_library\nfrom scapy.modules.six.moves import range\n\n\n# ctypes definitions\n\nLIBC = cdll.LoadLibrary(find_library(\"libc\"))\nLIBC.ioctl.argtypes = [c_int, c_ulong, c_char_p]\nLIBC.ioctl.restype = c_int\n\n\n# Addresses manipulation functions\n\ndef get_if_raw_addr(ifname):\n    \"\"\"Returns the IPv4 address configured on 'ifname', packed with inet_pton.\"\"\"\n\n    # Get ifconfig output\n    try:\n        fd = os.popen(\"%s %s\" % (conf.prog.ifconfig, ifname))\n    except OSError as msg:\n        warning(\"Failed to execute ifconfig: (%s)\", msg)\n        return b\"\\0\\0\\0\\0\"\n\n    # Get IPv4 addresses\n    addresses = [l for l in fd if l.find(\"netmask\") >= 0]\n    if not addresses:\n        warning(\"No IPv4 address found on %s !\", ifname)\n        return b\"\\0\\0\\0\\0\"\n\n    # Pack the first address\n    address = addresses[0].split(' ')[1]\n    return socket.inet_pton(socket.AF_INET, address)\n\n\ndef get_if_raw_hwaddr(ifname):\n    \"\"\"Returns the packed MAC address configured on 'ifname'.\"\"\"\n\n    NULL_MAC_ADDRESS = b'\\x00' * 6\n\n    # Handle the loopback interface separately\n    if ifname == LOOPBACK_NAME:\n        return (ARPHDR_LOOPBACK, NULL_MAC_ADDRESS)\n\n    # Get ifconfig output\n    try:\n        fd = os.popen(\"%s %s\" % (conf.prog.ifconfig, ifname))\n    except OSError as msg:\n        raise Scapy_Exception(\"Failed to execute ifconfig: (%s)\" % msg)\n\n    # Get MAC addresses\n    addresses = [l for l in fd.readlines() if l.find(\"ether\") >= 0 or\n                 l.find(\"lladdr\") >= 0 or\n                 l.find(\"address\") >= 0]\n    if not addresses:\n        raise Scapy_Exception(\"No MAC address found on %s !\" % ifname)\n\n    # Pack and return the MAC address\n    mac = addresses[0].split(' ')[1]\n    mac = [chr(int(b, 16)) for b in mac.split(':')]\n    return (ARPHDR_ETHER, ''.join(mac))\n\n\n# BPF specific functions\n\ndef get_dev_bpf():\n    \"\"\"Returns an opened BPF file object\"\"\"\n\n    # Get the first available BPF handle\n    for bpf in range(0, 8):\n        try:\n            fd = os.open(\"/dev/bpf%i\" % bpf, os.O_RDWR)\n            return (fd, bpf)\n        except OSError:\n            continue\n\n    raise Scapy_Exception(\"No /dev/bpf handle is available !\")\n\n\ndef attach_filter(fd, iface, bpf_filter_string):\n    \"\"\"Attach a BPF filter to the BPF file descriptor\"\"\"\n\n    # Retrieve the BPF byte code in decimal\n    command = \"%s -i %s -ddd -s 1600 '%s'\" % (conf.prog.tcpdump, iface, bpf_filter_string)\n    try:\n        f = os.popen(command)\n    except OSError as msg:\n        raise Scapy_Exception(\"Failed to execute tcpdump: (%s)\" % msg)\n\n    # Convert the byte code to a BPF program structure\n    lines = f.readlines()\n    if lines == []:\n        raise Scapy_Exception(\"Got an empty BPF filter from tcpdump !\")\n\n    bp = get_bpf_pointer(lines)\n    # Assign the BPF program to the interface\n    ret = LIBC.ioctl(c_int(fd), BIOCSETF, cast(pointer(bp), c_char_p))\n    if ret < 0:\n        raise Scapy_Exception(\"Can't attach the BPF filter !\")\n\n\n# Interface manipulation functions\n\ndef get_if_list():\n    \"\"\"Returns a list containing all network interfaces.\"\"\"\n\n    # Get ifconfig output\n    try:\n        fd = os.popen(\"%s -a\" % conf.prog.ifconfig)\n    except OSError as msg:\n        raise Scapy_Exception(\"Failed to execute ifconfig: (%s)\" % msg)\n\n    # Get interfaces\n    interfaces = [line[:line.find(':')] for line in fd.readlines()\n                  if \": flags\" in line.lower()]\n    return interfaces\n\n\ndef get_working_ifaces():\n    \"\"\"\n    Returns an ordered list of interfaces that could be used with BPF.\n    Note: the order mimics pcap_findalldevs() behavior\n    \"\"\"\n\n    # Only root is allowed to perform the following ioctl() call\n    if os.getuid() != 0:\n        return []\n\n    # Test all network interfaces\n    interfaces = []\n    for ifname in get_if_list():\n\n        # Unlike pcap_findalldevs(), we do not care of loopback interfaces.\n        if ifname == LOOPBACK_NAME:\n            continue\n\n        # Get interface flags\n        try:\n            result = get_if(ifname, SIOCGIFFLAGS)\n        except IOError:\n            warning(\"ioctl(SIOCGIFFLAGS) failed on %s !\", ifname)\n            continue\n\n        # Convert flags\n        ifflags = struct.unpack(\"16xH14x\", result)[0]\n        if ifflags & 0x1:  # IFF_UP\n\n            # Get a BPF handle\n            fd, _ = get_dev_bpf()\n            if fd is None:\n                raise Scapy_Exception(\"No /dev/bpf are available !\")\n\n            # Check if the interface can be used\n            try:\n                fcntl.ioctl(fd, BIOCSETIF, struct.pack(\"16s16x\", ifname.encode()))\n                interfaces.append((ifname, int(ifname[-1])))\n            except IOError:\n                pass\n\n            # Close the file descriptor\n            os.close(fd)\n\n    # Sort to mimic pcap_findalldevs() order\n    interfaces.sort(key=lambda elt: elt[1])\n\n    return interfaces\n\n\ndef get_working_if():\n    \"\"\"Returns the first interface than can be used with BPF\"\"\"\n\n    ifaces = get_working_ifaces()\n    if not ifaces:\n        # A better interface will be selected later using the routing table\n        return LOOPBACK_NAME\n    return ifaces[0][0]\n", "path": "scapy/arch/bpf/core.py"}], "after_files": [{"content": "# Guillaume Valadon <guillaume@valadon.net>\n\n\"\"\"\nScapy *BSD native support - core\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom scapy.config import conf\nfrom scapy.error import Scapy_Exception, warning\nfrom scapy.data import ARPHDR_LOOPBACK, ARPHDR_ETHER\nfrom scapy.arch.common import get_if, get_bpf_pointer\nfrom scapy.consts import LOOPBACK_NAME\n\nfrom scapy.arch.bpf.consts import *\n\nimport os\nimport socket\nimport fcntl\nimport struct\n\nfrom ctypes import cdll, cast, pointer, POINTER, Structure\nfrom ctypes import c_int, c_ulong, c_char_p\nfrom ctypes.util import find_library\nfrom scapy.modules.six.moves import range\n\n\n# ctypes definitions\n\nLIBC = cdll.LoadLibrary(find_library(\"libc\"))\nLIBC.ioctl.argtypes = [c_int, c_ulong, c_char_p]\nLIBC.ioctl.restype = c_int\n\n\n# Addresses manipulation functions\n\ndef get_if_raw_addr(ifname):\n    \"\"\"Returns the IPv4 address configured on 'ifname', packed with inet_pton.\"\"\"\n\n    # Get ifconfig output\n    try:\n        fd = os.popen(\"%s %s\" % (conf.prog.ifconfig, ifname))\n    except OSError as msg:\n        warning(\"Failed to execute ifconfig: (%s)\", msg)\n        return b\"\\0\\0\\0\\0\"\n\n    # Get IPv4 addresses\n    addresses = [l for l in fd if l.find(\"netmask\") >= 0]\n    if not addresses:\n        warning(\"No IPv4 address found on %s !\", ifname)\n        return b\"\\0\\0\\0\\0\"\n\n    # Pack the first address\n    address = addresses[0].split(' ')[1]\n    return socket.inet_pton(socket.AF_INET, address)\n\n\ndef get_if_raw_hwaddr(ifname):\n    \"\"\"Returns the packed MAC address configured on 'ifname'.\"\"\"\n\n    NULL_MAC_ADDRESS = b'\\x00' * 6\n\n    # Handle the loopback interface separately\n    if ifname == LOOPBACK_NAME:\n        return (ARPHDR_LOOPBACK, NULL_MAC_ADDRESS)\n\n    # Get ifconfig output\n    try:\n        fd = os.popen(\"%s %s\" % (conf.prog.ifconfig, ifname))\n    except OSError as msg:\n        raise Scapy_Exception(\"Failed to execute ifconfig: (%s)\" % msg)\n\n    # Get MAC addresses\n    addresses = [l for l in fd.readlines() if l.find(\"ether\") >= 0 or\n                 l.find(\"lladdr\") >= 0 or\n                 l.find(\"address\") >= 0]\n    if not addresses:\n        raise Scapy_Exception(\"No MAC address found on %s !\" % ifname)\n\n    # Pack and return the MAC address\n    mac = addresses[0].split(' ')[1]\n    mac = [chr(int(b, 16)) for b in mac.split(':')]\n    return (ARPHDR_ETHER, ''.join(mac))\n\n\n# BPF specific functions\n\ndef get_dev_bpf():\n    \"\"\"Returns an opened BPF file object\"\"\"\n\n    # Get the first available BPF handle\n    for bpf in range(256):\n        try:\n            fd = os.open(\"/dev/bpf%i\" % bpf, os.O_RDWR)\n            return (fd, bpf)\n        except OSError:\n            continue\n\n    raise Scapy_Exception(\"No /dev/bpf handle is available !\")\n\n\ndef attach_filter(fd, iface, bpf_filter_string):\n    \"\"\"Attach a BPF filter to the BPF file descriptor\"\"\"\n\n    # Retrieve the BPF byte code in decimal\n    command = \"%s -i %s -ddd -s 1600 '%s'\" % (conf.prog.tcpdump, iface, bpf_filter_string)\n    try:\n        f = os.popen(command)\n    except OSError as msg:\n        raise Scapy_Exception(\"Failed to execute tcpdump: (%s)\" % msg)\n\n    # Convert the byte code to a BPF program structure\n    lines = f.readlines()\n    if lines == []:\n        raise Scapy_Exception(\"Got an empty BPF filter from tcpdump !\")\n\n    bp = get_bpf_pointer(lines)\n    # Assign the BPF program to the interface\n    ret = LIBC.ioctl(c_int(fd), BIOCSETF, cast(pointer(bp), c_char_p))\n    if ret < 0:\n        raise Scapy_Exception(\"Can't attach the BPF filter !\")\n\n\n# Interface manipulation functions\n\ndef get_if_list():\n    \"\"\"Returns a list containing all network interfaces.\"\"\"\n\n    # Get ifconfig output\n    try:\n        fd = os.popen(\"%s -a\" % conf.prog.ifconfig)\n    except OSError as msg:\n        raise Scapy_Exception(\"Failed to execute ifconfig: (%s)\" % msg)\n\n    # Get interfaces\n    interfaces = [line[:line.find(':')] for line in fd.readlines()\n                  if \": flags\" in line.lower()]\n    return interfaces\n\n\ndef get_working_ifaces():\n    \"\"\"\n    Returns an ordered list of interfaces that could be used with BPF.\n    Note: the order mimics pcap_findalldevs() behavior\n    \"\"\"\n\n    # Only root is allowed to perform the following ioctl() call\n    if os.getuid() != 0:\n        return []\n\n    # Test all network interfaces\n    interfaces = []\n    for ifname in get_if_list():\n\n        # Unlike pcap_findalldevs(), we do not care of loopback interfaces.\n        if ifname == LOOPBACK_NAME:\n            continue\n\n        # Get interface flags\n        try:\n            result = get_if(ifname, SIOCGIFFLAGS)\n        except IOError:\n            warning(\"ioctl(SIOCGIFFLAGS) failed on %s !\", ifname)\n            continue\n\n        # Convert flags\n        ifflags = struct.unpack(\"16xH14x\", result)[0]\n        if ifflags & 0x1:  # IFF_UP\n\n            # Get a BPF handle\n            fd, _ = get_dev_bpf()\n            if fd is None:\n                raise Scapy_Exception(\"No /dev/bpf are available !\")\n\n            # Check if the interface can be used\n            try:\n                fcntl.ioctl(fd, BIOCSETIF, struct.pack(\"16s16x\", ifname.encode()))\n                interfaces.append((ifname, int(ifname[-1])))\n            except IOError:\n                pass\n\n            # Close the file descriptor\n            os.close(fd)\n\n    # Sort to mimic pcap_findalldevs() order\n    interfaces.sort(key=lambda elt: elt[1])\n\n    return interfaces\n\n\ndef get_working_if():\n    \"\"\"Returns the first interface than can be used with BPF\"\"\"\n\n    ifaces = get_working_ifaces()\n    if not ifaces:\n        # A better interface will be selected later using the routing table\n        return LOOPBACK_NAME\n    return ifaces[0][0]\n", "path": "scapy/arch/bpf/core.py"}]}