text stringlengths 81 112k |
|---|
Creates a temporary file.
:param keep: If False, automatically delete the file when Scapy exits.
:param autoext: Suffix to add to the generated file name.
:param fd: If True, this returns a file-like object with the temporary
file opened. If False (default), this returns a file path.
def ge... |
Creates a temporary file, and returns its name.
:param keep: If False (default), the directory will be recursively
deleted when Scapy exits.
:return: A full path to a temporary directory.
def get_temp_dir(keep=False):
"""Creates a temporary file, and returns its name.
:param keep: If... |
Restarts scapy
def restart():
"""Restarts scapy"""
if not conf.interactive or not os.path.isfile(sys.argv[0]):
raise OSError("Scapy was not started from console")
if WINDOWS:
try:
res_code = subprocess.call([sys.executable] + sys.argv)
except KeyboardInterrupt:
... |
Build a tcpdump like hexadecimal view
:param x: a Packet
:param dump: define if the result must be printed or returned in a variable
:returns: a String only when dump=True
def hexdump(x, dump=False):
"""Build a tcpdump like hexadecimal view
:param x: a Packet
:param dump: define if the result... |
Build an equivalent view of hexdump() on a single line
Note that setting both onlyasc and onlyhex to 1 results in a empty output
:param x: a Packet
:param onlyasc: 1 to display only the ascii view
:param onlyhex: 1 to display only the hexadecimal view
:param dump: print the view if False
:retu... |
Build a per byte hexadecimal representation
Example:
>>> chexdump(IP())
0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01 # noqa: E501
:param x: a Packet
:param dump: print the view if False
:returns: a String only i... |
Build a fancy tcpdump like hex from bytes.
def hexstr(x, onlyasc=0, onlyhex=0, color=False):
"""Build a fancy tcpdump like hex from bytes."""
x = bytes_encode(x)
_sane_func = sane_color if color else sane
s = []
if not onlyasc:
s.append(" ".join("%02X" % orb(b) for b in x))
if not onlyh... |
Show differences between 2 binary strings
def hexdiff(x, y):
"""Show differences between 2 binary strings"""
x = bytes_encode(x)[::-1]
y = bytes_encode(y)[::-1]
SUBST = 1
INSERT = 1
d = {(-1, -1): (0, (-1, -1))}
for j in range(len(y)):
d[-1, j] = d[-1, j - 1][0] + INSERT, (-1, j - 1... |
Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.
Including the bytes into the buffer (at the position marked by offset) the # noqa: E501
global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501
the integrity of the buffer on the receiver ... |
Returns a random string of length l (l >= 0)
def randstring(l):
"""
Returns a random string of length l (l >= 0)
"""
return b"".join(struct.pack('B', random.randint(0, 255)) for _ in range(l)) |
Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2
must be of same length.
def strxor(s1, s2):
"""
Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2
must be of same length.
"""
return b"".join(map(lambda x, y: chb(orb(x) ^ orb(y)), s1, s2)) |
do_graph(graph, prog=conf.prog.dot, format="svg",
target="| conf.prog.display", options=None, [string=1]):
string: if not None, simply return the graph string
graph: GraphViz graph description
format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option
target: filename or redirec... |
Pickle a Python object
def save_object(fname, obj):
"""Pickle a Python object"""
fd = gzip.open(fname, "wb")
six.moves.cPickle.dump(obj, fd)
fd.close() |
Corrupt a given percentage or number of bytes from a string
def corrupt_bytes(s, p=0.01, n=None):
"""Corrupt a given percentage or number of bytes from a string"""
s = array.array("B", bytes_encode(s))
s_len = len(s)
if n is None:
n = max(1, int(s_len * p))
for i in random.sample(range(s_le... |
Write a list of packets to a pcap file
filename: the name of the file to write packets to, or an open,
writable file-like object. The file descriptor will be
closed at the end of the call, so do not use an object you
do not want to close (e.g., running wrpcap(sys.stdout, [])
in ... |
Read a pcap or pcapng file and return a packet list
count: read only <count> packets
def rdpcap(filename, count=-1):
"""Read a pcap or pcapng file and return a packet list
count: read only <count> packets
"""
with PcapReader(filename) as fdesc:
return fdesc.read_all(count=count) |
Imports a tcpdump like hexadecimal view
e.g: exported via hexdump() or tcpdump or wireshark's "export as hex"
def import_hexcap():
"""Imports a tcpdump like hexadecimal view
e.g: exported via hexdump() or tcpdump or wireshark's "export as hex"
"""
re_extract_hexcap = re.compile(r"^((0x)?[0-9a-fA-... |
Runs Wireshark on a list of packets.
See :func:`tcpdump` for more parameter description.
Note: this defaults to wait=False, to run Wireshark in the background.
def wireshark(pktlist, wait=False, **kwargs):
"""
Runs Wireshark on a list of packets.
See :func:`tcpdump` for more parameter descriptio... |
Run tshark on a list of packets.
:param args: If not specified, defaults to ``tshark -V``.
See :func:`tcpdump` for more parameters.
def tdecode(pktlist, args=None, **kwargs):
"""
Run tshark on a list of packets.
:param args: If not specified, defaults to ``tshark -V``.
See :func:`tcpdump` f... |
Run tcpdump or tshark on a list of packets.
When using ``tcpdump`` on OSX (``prog == conf.prog.tcpdump``), this uses a
temporary file to store the packets. This works around a bug in Apple's
version of ``tcpdump``: http://apple.stackexchange.com/questions/152682/
Otherwise, the packets are passed in s... |
Run hexedit on a list of packets, then return the edited packets.
def hexedit(pktlist):
"""Run hexedit on a list of packets, then return the edited packets."""
f = get_temp_file()
wrpcap(f, pktlist)
with ContextManagerSubprocess("hexedit()", conf.prog.hexedit):
subprocess.call([conf.prog.hexedi... |
Get terminal width (number of characters) if in a window.
Notice: this will try several methods in order to
support as many terminals and OS as possible.
def get_terminal_width():
"""Get terminal width (number of characters) if in a window.
Notice: this will try several methods in order to
suppor... |
Pretty list to fit the terminal, and add header
def pretty_list(rtlst, header, sortBy=0, borders=False):
"""Pretty list to fit the terminal, and add header"""
if borders:
_space = "|"
else:
_space = " "
# Windows has a fat terminal border
_spacelen = len(_space) * (len(header) - 1)... |
Core function of the make_table suite, which generates the table
def __make_table(yfmtfunc, fmtfunc, endline, data, fxyz, sortx=None, sorty=None, seplinefunc=None): # noqa: E501
"""Core function of the make_table suite, which generates the table"""
vx = {}
vy = {}
vz = {}
vxf = {}
# Python 2 ... |
Whois client for Python
def whois(ip_address):
"""Whois client for Python"""
whois_ip = str(ip_address)
try:
query = socket.gethostbyname(whois_ip)
except Exception:
query = whois_ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.ripe.net", 43))
s.se... |
Open (if necessary) filename, and read the magic.
def open(filename):
"""Open (if necessary) filename, and read the magic."""
if isinstance(filename, six.string_types):
try:
fdesc = gzip.open(filename, "rb")
magic = fdesc.read(4)
except IOError:
... |
return a list of all packets in the pcap file
def read_all(self, count=-1):
"""return a list of all packets in the pcap file
"""
res = []
while count != 0:
count -= 1
p = self.read_packet()
if p is None:
break
res.append(p)... |
Read blocks until it reaches either EOF or a packet, and
returns None or (packet, (linktype, sec, usec, wirelen)),
where packet is a string.
def read_packet(self, size=MTU):
"""Read blocks until it reaches either EOF or a packet, and
returns None or (packet, (linktype, sec, usec, wirele... |
Interface Description Block
def read_block_idb(self, block, _):
"""Interface Description Block"""
options = block[16:]
tsresol = 1000000
while len(options) >= 4:
code, length = struct.unpack(self.endian + "HH", options[:4])
# PCAP Next Generation (pcapng) Capture... |
Enhanced Packet Block
def read_block_epb(self, block, size):
"""Enhanced Packet Block"""
intid, tshigh, tslow, caplen, wirelen = struct.unpack(
self.endian + "5I",
block[:20],
)
return (block[20:20 + caplen][:size],
RawPcapNgReader.PacketMetadata(... |
Writes a Packet or bytes to a pcap file.
:param pkt: Packet(s) to write (one record for each Packet), or raw
bytes to write (as one record).
:type pkt: iterable[Packet], Packet or bytes
def write(self, pkt):
"""
Writes a Packet or bytes to a pcap file.
:par... |
Writes a single packet to the pcap file.
:param packet: Packet, or bytes for a single packet
:type packet: Packet or bytes
:param sec: time the packet was captured, in seconds since epoch. If
not supplied, defaults to now.
:type sec: int or long
:param usec: ... |
Play VoIP packets with RAW data that
are either sniffed either from an IP, or
specified as a list.
It will play only the incoming packets !
:param s1: The IP of the src of all VoIP packets.
:param lst: (optional) A list of packets to load
:type s1: string
:type lst: list
:Example:
... |
Same than voip_play, but will play
both incoming and outcoming packets.
The sound will surely suffer distortion.
Only supports sniffing.
.. seealso:: voip_play
to play only incoming packets.
def voip_play2(s1, **kargs):
"""
Same than voip_play, but will play
both incoming and outcomin... |
We expect this. If tls_version is not set, this means we did not process
any complete ClientHello, so we're most probably reading/building a
signature_algorithms extension, hence we cannot be in phantom_mode.
However, if the tls_version has been set, we test for TLS 1.2.
def phantom_mode(pkt):
"""
... |
Decorator for version-dependent fields.
If get_or_add is True (means get), we return s, self.phantom_value.
If it is False (means add), we return s.
def phantom_decorate(f, get_or_add):
"""
Decorator for version-dependent fields.
If get_or_add is True (means get), we return s, self.phantom_value.
... |
With SSLv2 you will never be able to add a sig_len.
def addfield(self, pkt, s, val):
"""With SSLv2 you will never be able to add a sig_len."""
v = pkt.tls_session.tls_version
if v and v < 0x0300:
return s
return super(SigLenField, self).addfield(pkt, s, val) |
Sign 'm' with the PrivKey 'key' and update our own 'sig_val'.
Note that, even when 'sig_alg' is not None, we use the signature scheme
of the PrivKey (neither do we care to compare the both of them).
def _update_sig(self, m, key):
"""
Sign 'm' with the PrivKey 'key' and update our own 's... |
Verify that our own 'sig_val' carries the signature of 'm' by the
key associated to the Cert 'cert'.
def _verify_sig(self, m, cert):
"""
Verify that our own 'sig_val' carries the signature of 'm' by the
key associated to the Cert 'cert'.
"""
if self.sig_val:
... |
We do not want TLSServerKeyExchange.build() to overload and recompute
things every time it is called. This method can be called specifically
to have things filled in a smart fashion.
Note that we do not expect default_params.g to be more than 0xff.
def fill_missing(self):
"""
W... |
XXX Check that the pubkey received is in the group.
def register_pubkey(self):
"""
XXX Check that the pubkey received is in the group.
"""
p = pkcs_os2ip(self.dh_p)
g = pkcs_os2ip(self.dh_g)
pn = dh.DHParameterNumbers(p, g)
y = pkcs_os2ip(self.dh_Ys)
pub... |
We do not want TLSServerKeyExchange.build() to overload and recompute
things every time it is called. This method can be called specifically
to have things filled in a smart fashion.
XXX We should account for the point_format (before 'point' filling).
def fill_missing(self):
"""
... |
XXX Support compressed point format.
XXX Check that the pubkey received is on the curve.
def register_pubkey(self):
"""
XXX Support compressed point format.
XXX Check that the pubkey received is on the curve.
"""
# point_format = 0
# if self.point[0] in [b'\x02',... |
First we update the client DHParams. Then, we try to update the server
DHParams generated during Server*DHParams building, with the shared
secret. Finally, we derive the session keys and update the context.
def post_dissection(self, m):
"""
First we update the client DHParams. Then, we ... |
We encrypt the premaster secret (the 48 bytes) with either the server
certificate or the temporary RSA key provided in a server key exchange
message. After that step, we add the 2 bytes to provide the length, as
described in implementation notes at the end of section 7.4.7.1.
def post_build(sel... |
Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y
def lambda_tuple_converter(func):
"""
Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y
"""
if func is not None and func.__code__.c... |
Turn base64 into bytes
def base64_bytes(x):
"""Turn base64 into bytes"""
if six.PY2:
return base64.decodestring(x)
return base64.decodebytes(bytes_encode(x)) |
Turn bytes into base64
def bytes_base64(x):
"""Turn bytes into base64"""
if six.PY2:
return base64.encodestring(x).replace('\n', '')
return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'') |
Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield().
def m2i(self, pkt, m):
"""
Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by... |
If the decryption of the content did not fail with a CipherError,
we begin a loop on the clear content in order to get as much messages
as possible, of the type advertised in the record header. This is
notably important for several TLS handshake implementations, which
may for instance pa... |
Update the context with information from the built packet.
If no type was given at the record layer, we try to infer it.
def i2m(self, pkt, p):
"""
Update the context with information from the built packet.
If no type was given at the record layer, we try to infer it.
"""
... |
Reconstruct the header because the TLS type may have been updated.
Then, append the content.
def addfield(self, pkt, s, val):
"""
Reconstruct the header because the TLS type may have been updated.
Then, append the content.
"""
res = b""
for p in val:
... |
If the TLS class was called on raw SSLv2 data, we want to return an
SSLv2 record instance. We acknowledge the risk of SSLv2 packets with a
msglen of 0x1403, 0x1503, 0x1603 or 0x1703 which will never be casted
as SSLv2 records but TLS ones instead, but hey, we can't be held
responsible fo... |
Provided with the record header, the TLSCompressed.fragment and the
HMAC, return True if the HMAC is correct. If we could not compute the
HMAC because the key was missing, there is no sense in verifying
anything, thus we also return True.
Meant to be used with a block cipher or a stream... |
Provided with the TLSCompressed.fragment,
return the TLSPlaintext.fragment.
def _tls_decompress(self, s):
"""
Provided with the TLSCompressed.fragment,
return the TLSPlaintext.fragment.
"""
alg = self.tls_session.rcs.compression
return alg.decompress(s) |
Decrypt, verify and decompress the message,
i.e. apply the previous methods according to the reading cipher type.
If the decryption was successful, 'len' will be the length of the
TLSPlaintext.fragment. Else, it should be the length of the
_TLSEncryptedContent.
def pre_dissect(self, s):... |
Commit the pending r/w state if it has been triggered (e.g. by an
underlying TLSChangeCipherSpec or a SSLv2ClientMasterKey). We update
nothing if the prcs was not set, as this probably means that we're
working out-of-context (and we need to keep the default rcs).
def post_dissect(self, s):
... |
Provided with the TLSPlaintext.fragment,
return the TLSCompressed.fragment.
def _tls_compress(self, s):
"""
Provided with the TLSPlaintext.fragment,
return the TLSCompressed.fragment.
"""
alg = self.tls_session.wcs.compression
return alg.compress(s) |
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here.
def _tls_auth_encrypt(self, s):
"""
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is ... |
Provided with the record header (concatenation of the TLSCompressed
type, version and length fields) and the TLSCompressed.fragment,
return the concatenation of the TLSCompressed.fragment and the HMAC.
Meant to be used with a block cipher or a stream cipher.
It would fail with an AEAD c... |
Provided with the concatenation of the TLSCompressed.fragment and the
HMAC, append the right padding and return it as a whole.
This is the TLS-style padding: while SSL allowed for random padding,
TLS (misguidedly) specifies the repetition of the same byte all over,
and this byte must be ... |
Apply the previous methods according to the writing cipher type.
def post_build(self, pkt, pay):
"""
Apply the previous methods according to the writing cipher type.
"""
# Compute the length of TLSPlaintext fragment
hdr, frag = pkt[:5], pkt[5:]
tmp_len = len(frag)
... |
This function is called during sendrecv() routine to select
the available sockets.
params:
- sockets: an array of sockets that need to be selected
returns:
- an array of sockets that were selected
- the function to be called next to get the packets (i.g. recv)
def se... |
Open the TUN or TAP device.
def open(self):
"""Open the TUN or TAP device."""
if not self.closed:
return
self.outs = self.ins = open(
"/dev/net/tun" if LINUX else ("/dev/%s" % self.iface), "r+b",
buffering=0
)
if LINUX:
from fcntl ... |
Calculate the length of the attribute value field
def util_mic_len(pkt):
''' Calculate the length of the attribute value field '''
if (pkt.nwk_seclevel == 0): # no encryption, no mic
return 0
elif (pkt.nwk_seclevel == 1): # MIC-32
return 4
elif (pkt.nwk_seclevel == 2): # MIC-64
... |
Builds a list of EIR messages to wrap this frame.
def build_eir(self):
"""Builds a list of EIR messages to wrap this frame."""
return LowEnergyBeaconHelper.base_eir + [
EIR_Hdr() / EIR_CompleteList16BitServiceUUIDs(svc_uuids=[
EDDYSTONE_UUID]),
EIR_Hdr() / EIR_S... |
Creates an Eddystone_Frame with a Eddystone_URL for a given URL.
def from_url(url):
"""Creates an Eddystone_Frame with a Eddystone_URL for a given URL."""
url = url.encode('ascii')
scheme = None
for k, v in EDDYSTONE_URL_SCHEMES.items():
if url.startswith(v):
... |
Ex:
add(dst="2001:db8:cafe:f000::/56")
add(dst="2001:db8:cafe:f000::/56", gw="2001:db8:cafe::1")
add(dst="2001:db8:cafe:f000::/64", gw="2001:db8:cafe::1", dev="eth0")
def add(self, *args, **kargs):
"""Ex:
add(dst="2001:db8:cafe:f000::/56")
add(dst="2001:db8:cafe:f000::/5... |
removes all route entries that uses 'iff' interface.
def ifdel(self, iff):
""" removes all route entries that uses 'iff' interface. """
new_routes = []
for rt in self.routes:
if rt[3] != iff:
new_routes.append(rt)
self.invalidate_cache()
self.routes =... |
Add an interface 'iff' with provided address into routing table.
Ex: ifadd('eth0', '2001:bd8:cafe:1::1/64') will add following entry into # noqa: E501
Scapy6 internal routing table:
Destination Next Hop iface Def src @ Metric
2001:bd8:cafe:1::/64 :: ... |
Provide best route to IPv6 destination address, based on Scapy
internal routing table content.
When a set of address is passed (e.g. 2001:db8:cafe:*::1-5) an address
of the set is used. Be aware of that behavior when using wildcards in
upper parts of addresses !
If 'dst' parame... |
Compress p (a TLSPlaintext instance) using compression algorithm instance
alg and return a TLSCompressed instance.
def _tls_compress(alg, p):
"""
Compress p (a TLSPlaintext instance) using compression algorithm instance
alg and return a TLSCompressed instance.
"""
c = TLSCompressed()
c.type... |
Decompress c (a TLSCompressed instance) using compression algorithm
instance alg and return a TLSPlaintext instance.
def _tls_decompress(alg, c):
"""
Decompress c (a TLSCompressed instance) using compression algorithm
instance alg and return a TLSPlaintext instance.
"""
p = TLSPlaintext()
p... |
Compute the MAC using provided MAC alg instance over TLSCiphertext c using
current write sequence number write_seq_num. Computed MAC is then appended
to c.data and c.len is updated to reflect that change. It is the
caller responsibility to increment the sequence number after the operation.
The function ... |
Verify if the MAC in provided message (message resulting from decryption
and padding removal) is valid. Current read sequence number is used in
the verification process.
If the MAC is valid:
- The function returns True
- The packet p is updated in the following way: trailing MAC value is
r... |
Provided with cipher block size parameter and current TLSCompressed packet
p (after MAC addition), the function adds required, deterministic padding
to p.data before encryption step, as it is defined for TLS (i.e. not
SSL and its allowed random padding). The function has no return value.
def _tls_add_pad(p... |
Provided with a just decrypted TLSCiphertext (now a TLSPlaintext instance)
p, the function removes the trailing padding found in p.data. It also
performs some sanity checks on the padding (length, content, ...). False
is returned if one of the check fails. Otherwise, True is returned,
indicating that p.... |
Provided with an already MACed TLSCompressed packet, and a stream or block
cipher alg, the function converts it into a TLSCiphertext (i.e. encrypts it
and updates length). The function returns a newly created TLSCiphertext
instance.
def _tls_encrypt(alg, p):
"""
Provided with an already MACed TLSCo... |
Provided with a TLSCiphertext instance c, and a stream or block cipher alg,
the function decrypts c.data and returns a newly created TLSPlaintext.
def _tls_decrypt(alg, c):
"""
Provided with a TLSCiphertext instance c, and a stream or block cipher alg,
the function decrypts c.data and returns a newly c... |
Provided with a TLSCompressed instance p, the function applies AEAD
cipher alg to p.data and builds a new TLSCiphertext instance. Unlike
for block and stream ciphers, for which the authentication step is done
separately, AEAD alg does it simultaneously: this is the reason why
write_seq_num is passed to ... |
Provided with a TLSCiphertext instance c, the function applies AEAD
cipher alg auth_decrypt function to c.data (and additional data)
in order to authenticate the data and decrypt c.data. When those
steps succeed, the result is a newly created TLSCompressed instance.
On error, None is returned. Note that... |
Function used to call a program using the extcap format,
then parse the results
def _extcap_call(prog, args, keyword, values):
"""Function used to call a program using the extcap format,
then parse the results"""
p = subprocess.Popen(
[prog] + args,
stdout=subprocess.PIPE, stderr=subpro... |
Builds a list of _HCSINullField with numbered "Reserved" names.
Takes the same arguments as the ``range`` built-in.
:returns: list[HCSINullField]
def _hcsi_null_range(*args, **kwargs):
"""Builds a list of _HCSINullField with numbered "Reserved" names.
Takes the same arguments as the ``range`` built-... |
Convert internal value to machine value
def i2m(self, pkt, x):
"""Convert internal value to machine value"""
if x is None:
# Try to return zero if undefined
x = self.h2i(pkt, 0)
return x |
Returns the main global unicast address associated with provided
interface, in human readable form. If no global address is found,
None is returned.
def get_if_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in human readable form. If no global address is... |
Returns the main global unicast address associated with provided
interface, in network format. If no global address is found, None
is returned.
def get_if_raw_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in network format. If no global address is found... |
Get representation name of a pnio frame ID
:param x: a key of the PNIO_FRAME_IDS dictionary
:returns: str
def i2s_frameid(x):
""" Get representation name of a pnio frame ID
:param x: a key of the PNIO_FRAME_IDS dictionary
:returns: str
"""
try:
return PNIO_FRAME_IDS[x]
except ... |
Get pnio frame ID from a representation name
Performs a reverse look-up in PNIO_FRAME_IDS dictionary
:param x: a value of PNIO_FRAME_IDS dict
:returns: integer
def s2i_frameid(x):
""" Get pnio frame ID from a representation name
Performs a reverse look-up in PNIO_FRAME_IDS dictionary
:param... |
Attribution of correct type depending on version and pdu_type
def dispatch_hook(cls, _pkt=None, *args, **kargs):
'''
Attribution of correct type depending on version and pdu_type
'''
if _pkt and len(_pkt) >= 2:
version = orb(_pkt[0])
pdu_type = orb(_pkt[1])
... |
Parse bulk cymru data
def parse(self, data):
"""Parse bulk cymru data"""
ASNlist = []
for line in data.splitlines()[1:]:
line = plain_str(line)
if "|" not in line:
continue
asn, ip, desc = [elt.strip() for elt in line.split('|')]
... |
Encode and replace the mrcode value to its IGMPv3 encoded time value if needed, # noqa: E501
as specified in rfc3376#section-4.1.1.
If value < 128, return the value specified. If >= 128, encode as a floating # noqa: E501
point value. Value can be 0 - 31744.
def encode_maxrespcode(self):
... |
This can be used as a class decorator; if we want to support Python
2.5, we have to replace
@_register_lltd_specific_class(x[, y[, ...]])
class LLTDAttributeSpecific(LLTDAttribute):
[...]
by
class LLTDAttributeSpecific(LLTDAttribute):
[...]
LLTDAttributeSpecific = _register_lltd_specific_class(x[, y[, ...]])(
... |
Update the builder using the provided `plist`. `plist` can
be either a Packet() or a PacketList().
def parse(self, plist):
"""Update the builder using the provided `plist`. `plist` can
be either a Packet() or a PacketList().
"""
if not isinstance(plist, PacketList):
... |
Returns a dictionary object, keys are strings "source >
destincation [content type]", and values are the content
fetched, also as a string.
def get_data(self):
"""Returns a dictionary object, keys are strings "source >
destincation [content type]", and values are the content
fet... |
Convert an IPv6 address from text representation into binary form,
used when socket.inet_pton is not available.
def _inet6_pton(addr):
"""Convert an IPv6 address from text representation into binary form,
used when socket.inet_pton is not available.
"""
joker_pos = None
result = b""
addr = plain_s... |
Convert an IP address from text representation into binary form.
def inet_pton(af, addr):
"""Convert an IP address from text representation into binary form."""
# Will replace Net/Net6 objects
addr = plain_str(addr)
# Use inet_pton if available
try:
return socket.inet_pton(af, addr)
exc... |
Convert an IPv6 address from binary form into text representation,
used when socket.inet_pton is not available.
def _inet6_ntop(addr):
"""Convert an IPv6 address from binary form into text representation,
used when socket.inet_pton is not available.
"""
# IPv6 addresses have 128bits (16 bytes)
if len(... |
Convert an IP address from binary form into text representation.
def inet_ntop(af, addr):
"""Convert an IP address from binary form into text representation."""
# Use inet_ntop if available
addr = bytes_encode(addr)
try:
return socket.inet_ntop(af, addr)
except AttributeError:
try:
... |
Receives a packet, then returns a tuple containing (cls, pkt_data, time)
def recv_raw(self, x=MTU):
"""Receives a packet, then returns a tuple containing (cls, pkt_data, time)""" # noqa: E501
ll = self.ins.datalink()
if ll in conf.l2types:
cls = conf.l2types[ll]
else:
... |
Receives and dissect a packet in non-blocking mode.
Note: on Windows, this won't do anything.
def nonblock_recv(self):
"""Receives and dissect a packet in non-blocking mode.
Note: on Windows, this won't do anything."""
self.ins.setnonblock(1)
p = self.recv(MTU)
self.ins.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.