MCPcopy Index your code
hub / github.com/secdev/scapy / compile_filter

Function compile_filter

scapy/arch/common.py:66–132  ·  view source on GitHub ↗

Asks libpcap to parse the filter, then build the matching BPF bytecode. :param iface: if provided, use the interface to compile :param linktype: if provided, use the linktype to compile

(filter_exp,  # type: str
                   iface=None,  # type: Optional[Union[str, 'scapy.interfaces.NetworkInterface']]  # noqa: E501
                   linktype=None,  # type: Optional[int]
                   promisc=False  # type: bool
                   )

Source from the content-addressed store, hash-verified

64
65
66def compile_filter(filter_exp, # type: str
67 iface=None, # type: Optional[Union[str, 'scapy.interfaces.NetworkInterface']] # noqa: E501
68 linktype=None, # type: Optional[int]
69 promisc=False # type: bool
70 ):
71 # type: (...) -> bpf_program
72 """Asks libpcap to parse the filter, then build the matching
73 BPF bytecode.
74
75 :param iface: if provided, use the interface to compile
76 :param linktype: if provided, use the linktype to compile
77 """
78 try:
79 from scapy.libs.winpcapy import (
80 PCAP_ERRBUF_SIZE,
81 pcap_open_live,
82 pcap_compile,
83 pcap_compile_nopcap,
84 pcap_close
85 )
86 except OSError:
87 raise ImportError(
88 "libpcap is not available. Cannot compile filter !"
89 )
90 from ctypes import create_string_buffer
91 bpf = bpf_program()
92 bpf_filter = create_string_buffer(filter_exp.encode("utf8"))
93 if not linktype:
94 # Try to guess linktype to avoid root
95 if not iface:
96 if not conf.iface:
97 raise Scapy_Exception(
98 "Please provide an interface or linktype!"
99 )
100 iface = conf.iface
101 # Try to guess linktype to avoid requiring root
102 try:
103 arphd = resolve_iface(iface).type
104 linktype = ARPHRD_TO_DLT.get(arphd)
105 except Exception:
106 # Failed to use linktype: use the interface
107 pass
108 if linktype is not None:
109 # Some conversion aliases (e.g. linktype_to_dlt in libpcap)
110 if linktype == DLT_RAW_ALT:
111 linktype = DLT_RAW
112 ret = pcap_compile_nopcap(
113 MTU, linktype, ctypes.byref(bpf), bpf_filter, 1, -1
114 )
115 elif iface:
116 err = create_string_buffer(PCAP_ERRBUF_SIZE)
117 iface_b = create_string_buffer(network_name(iface).encode("utf8"))
118 pcap = pcap_open_live(
119 iface_b, MTU, promisc, 0, err
120 )
121 error = decode_locale_str(bytearray(err).strip(b"\x00"))
122 if error:
123 raise OSError(error)

Callers 3

tcpdumpFunction · 0.90
attach_filterFunction · 0.90
attach_filterFunction · 0.90

Calls 7

bpf_programClass · 0.90
Scapy_ExceptionClass · 0.90
resolve_ifaceFunction · 0.90
network_nameFunction · 0.90
decode_locale_strFunction · 0.90
encodeMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected