class ConfClass(object):
class Interceptor(object):
class ProgPath(ConfClass):
class ConfigFieldList:
class Emphasize(ConfigFieldList):
class Resolve(ConfigFieldList):
class Num2Layer:
class LayersList(List[Type['scapy.packet.Packet']]):
class CommandsList(List[Callable[..., Any]]):
class CacheInstance(Dict[str, Any], object):
class NetCache:
class Conf(ConfClass):
    def configure(self, cnf):
    def __repr__(self):
    def __str__(self):
    def __init__(self,
                 name,  # type: str
                 default,  # type: Any
                 hook,  # type: Callable[..., Any]
                 args=None,  # type: Optional[List[Any]]
                 kargs=None  # type: Optional[Dict[str, Any]]
                 ):
    def __get__(self, obj, typ=None):
    def set_from_hook(obj, name, val):
    def __set__(self, obj, val):
def _readonly(name):
    def __init__(self):
    def _is_field(f):
    def _recalc_layer_list(self):
    def add(self, *flds):
    def remove(self, *flds):
    def __contains__(self, elt):
    def __repr__(self):
    def __init__(self):
    def register(self, num, layer):
    def register_num2layer(self, num, layer):
    def register_layer2num(self, num, layer):
    def __getitem__(self, item):
    def __contains__(self, item):
    def get(self,
            item,  # type: Union[int, Type[Packet]]
            default=None,  # type: Optional[Type[Packet]]
            ):
    def __repr__(self):
    def __init__(self):
    def __repr__(self):
    def register(self, layer):
    def layers(self):
    def filter(self, items):
    def unfilter(self):
    def __repr__(self):
    def register(self, cmd):
def lsc():
    def __init__(self, name="noname", timeout=None):
    def flush(self):
    def __getitem__(self, item):
    def get(self, item, default=None):
    def __setitem__(self, item, v):
    def update(self,  # type: ignore
               other,  # type: Any
               **kwargs  # type: Any
               ):
    def iteritems(self):
    def iterkeys(self):
    def __iter__(self):
    def itervalues(self):
    def items(self):
    def keys(self):
    def values(self):
    def __len__(self):
    def summary(self):
    def __repr__(self):
    def copy(self):
    def __init__(self):
    def add_cache(self, cache):
    def new_cache(self, name, timeout=None):
    def __delattr__(self, attr):
    def update(self, other):
    def flush(self):
    def __repr__(self):
def _version_checker(module, minver):
def isCryptographyValid():
def isCryptographyAdvanced():
def isPyPy():
def _prompt_changer(attr, val, old):
def _set_conf_sockets():
def _socket_changer(attr, val, old):
def _loglevel_changer(attr, val, old):
def _iface_changer(attr, val, old):
    def __getattribute__(self, attr):
def crypto_validator(func):
    def func_in(*args, **kwargs):
def scapy_delete_temp_files(): class DADict(Generic[_K, _V]):
    """
    Direct Access Dictionary

    This acts like a dict, but it provides a direct attribute access
    to its keys through its values. This is used to store protocols,
    manuf...

    For instance, scapy fields will use a DADict as an enum::

        ETHER_TYPES[2048] -> IPv4

    Whereas humans can access::

        ETHER_TYPES.IPv4 -> 2048
    """
    def __init__(self, _name="DADict", **kargs):
        # type: (str, **Any) -> None
        self._name = _name
        self.d = {}  # type: Dict[_K, _V]
        self.update(kargs)

    def ident(self, v):
        # type: (_V) -> str
        """
        Return value that is used as key for the direct access
        """
        if isinstance(v, (str, bytes)):
            return fixname(v)
        return "unknown"

    def update(self, *args, **kwargs):
        # type: (*Dict[str, _V], **Dict[str, _V]) -> None
        for k, v in six.iteritems(dict(*args, **kwargs)):
            self[k] = v

    def iterkeys(self):
        # type: () -> Iterator[_K]
        for x in six.iterkeys(self.d):
            if not isinstance(x, str) or x[0] != "_":
                yield x

    def keys(self):
        # type: () -> List[_K]
        return list(self.iterkeys())

    def __iter__(self):
        # type: () -> Iterator[_K]
        return self.iterkeys()

    def itervalues(self):
        # type: () -> Iterator[_V]
        return six.itervalues(self.d)  # type: ignore

    def values(self):
        # type: () -> List[_V]
        return list(self.itervalues())

    def _show(self):
        # type: () -> None
        for k in self.iterkeys():
            print("%10s = %r" % (k, self[k]))

    def __repr__(self):
        # type: () -> str
        return "<%s - %s elements>" % (self._name, len(self))

    def __getitem__(self, attr):
        # type: (_K) -> _V
        return self.d[attr]

    def __setitem__(self, attr, val):
        # type: (_K, _V) -> None
        self.d[attr] = val

    def __len__(self):
        # type: () -> int
        return len(self.d)

    def __nonzero__(self):
        # type: () -> bool
        # Always has at least its name
        return len(self) > 1
    __bool__ = __nonzero__

    def __getattr__(self, attr):
        # type: (str) -> _K
        try:
            return object.__getattribute__(self, attr)  # type: ignore
        except AttributeError:
            for k, v in six.iteritems(self.d):
                if self.ident(v) == attr:
                    return cast(_K, k)
        raise AttributeError

    def __dir__(self):
        # type: () -> List[str]
        return [self.ident(x) for x in self.itervalues()] class RandBin(RandString):
    def __init__(self, size=None):
        # type: (Optional[Union[int, RandNum]]) -> None
        super(RandBin, self).__init__(
            size=size,
            chars=b"".join(chb(c) for c in range(256))
        )

    def _command_args(self):
        # type: () -> str
        if not isinstance(self.size, VolatileValue):
            return "size=%r" % self.size

        if isinstance(self.size, RandNumExpo) and \
                self.size.lambd == 0.01 and self.size.base == 0:
            # Default size for RandString, skip
            return ""
        return "size=%r" % self.size.command() class RandByte(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, 0, 2**8 - 1) class RandEnumKeys(RandEnum):
    """Picks a random value from dict keys list. """

    def __init__(self, enum, seed=None):
        # type: (Dict[Any, Any], Optional[int]) -> None
        self.enum = list(enum)
        RandEnum.__init__(self, 0, len(self.enum) - 1, seed)

    def _command_args(self):
        # type: () -> str
        # Note: only outputs the list of keys, but values are irrelevant anyway
        ret = "enum=%r" % self.enum
        if self._seed:
            ret += ", seed=%r" % self._seed
        return ret

    def _fix(self):
        # type: () -> Any
        return self.enum[next(self.seq)] class RandInt(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, 0, 2**32 - 1) class RandIP(_RandString[str]):
    _DEFAULT_IPTEMPLATE = "0.0.0.0/0"

    def __init__(self, iptemplate=_DEFAULT_IPTEMPLATE):
        # type: (str) -> None
        super(RandIP, self).__init__()
        self.ip = Net(iptemplate)

    def _command_args(self):
        # type: () -> str
        rep = "%s/%s" % (self.ip.net, self.ip.mask)
        if rep == self._DEFAULT_IPTEMPLATE:
            return ""
        return "iptemplate=%r" % rep

    def _fix(self):
        # type: () -> str
        return self.ip.choice() class RandIP6(_RandString[str]):
    def __init__(self, ip6template="**"):
        # type: (str) -> None
        super(RandIP6, self).__init__()
        self.tmpl = ip6template
        self.sp = []  # type: List[Union[int, RandNum, str]]
        for v in self.tmpl.split(":"):
            if not v or v == "**":
                self.sp.append(v)
                continue
            if "-" in v:
                a, b = v.split("-")
            elif v == "*":
                a = b = ""
            else:
                a = b = v

            if not a:
                a = "0"
            if not b:
                b = "ffff"
            if a == b:
                self.sp.append(int(a, 16))
            else:
                self.sp.append(RandNum(int(a, 16), int(b, 16)))
        self.variable = "" in self.sp
        self.multi = self.sp.count("**")

    def _command_args(self):
        # type: () -> str
        if self.tmpl == "**":
            return ""
        return "ip6template=%r" % self.tmpl

    def _fix(self):
        # type: () -> str
        nbm = self.multi
        ip = []  # type: List[str]
        for i, n in enumerate(self.sp):
            if n == "**":
                nbm -= 1
                remain = 8 - (len(self.sp) - i - 1) - len(ip) + nbm
                if "" in self.sp:
                    remain += 1
                if nbm or self.variable:
                    remain = random.randint(0, remain)
                for j in range(remain):
                    ip.append("%04x" % random.randint(0, 65535))
            elif isinstance(n, RandNum):
                ip.append("%04x" % int(n))
            elif n == 0:
                ip.append("0")
            elif not n:
                ip.append("")
            else:
                ip.append("%04x" % int(n))
        if len(ip) == 9:
            ip.remove("")
        if ip[-1] == "":
            ip[-1] = "0"
        return ":".join(ip) class RandLong(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, 0, 2**64 - 1) class RandMAC(_RandString[str]):
    def __init__(self, _template="*"):
        # type: (str) -> None
        super(RandMAC, self).__init__()
        self._template = _template
        _template += ":*:*:*:*:*"
        template = _template.split(":")
        self.mac = ()  # type: Tuple[Union[int, RandNum], ...]
        for i in range(6):
            v = 0  # type: Union[int, RandNum]
            if template[i] == "*":
                v = RandByte()
            elif "-" in template[i]:
                x, y = template[i].split("-")
                v = RandNum(int(x, 16), int(y, 16))
            else:
                v = int(template[i], 16)
            self.mac += (v,)

    def _command_args(self):
        # type: () -> str
        if self._template == "*":
            return ""
        return "template=%r" % self._template

    def _fix(self):
        # type: () -> str
        return "%02x:%02x:%02x:%02x:%02x:%02x" % self.mac  # type: ignore class RandNum(_RandNumeral[int]):
    """Instances evaluate to random integers in selected range"""
    min = 0
    max = 0

    def __init__(self, min, max):
        # type: (int, int) -> None
        self.min = min
        self.max = max

    def _command_args(self):
        # type: () -> str
        if self.__class__.__name__ == 'RandNum':
            return "min=%r, max=%r" % (self.min, self.max)
        return super(RandNum, self)._command_args()

    def _fix(self):
        # type: () -> int
        return random.randrange(self.min, self.max + 1)

    def __lshift__(self, other):
        # type: (int) -> int
        return self._fix() << other

    def __rshift__(self, other):
        # type: (int) -> int
        return self._fix() >> other

    def __and__(self, other):
        # type: (int) -> int
        return self._fix() & other

    def __rand__(self, other):
        # type: (int) -> int
        return other & self._fix()

    def __or__(self, other):
        # type: (int) -> int
        return self._fix() | other

    def __ror__(self, other):
        # type: (int) -> int
        return other | self._fix() class RandShort(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, 0, 2**16 - 1) class RandSInt(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, -2**31, 2**31 - 1) class RandSByte(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, -2**7, 2**7 - 1) class RandTermString(RandBin):
    def __init__(self, size, term):
        # type: (Union[int, RandNum], bytes) -> None
        self.term = bytes_encode(term)
        super(RandTermString, self).__init__(size=size)

    def _command_args(self):
        # type: () -> str
        return ", ".join((super(RandTermString, self)._command_args(),
                          "term=%r" % self.term))

    def _fix(self):
        # type: () -> bytes
        return RandBin._fix(self) + self.term class RandUUID(RandField[uuid.UUID]):
    """Generates a random UUID.

    By default, this generates a RFC 4122 version 4 UUID (totally random).

    See Python's ``uuid`` module documentation for more information.

    Args:
        template (optional): A template to build the UUID from. Not valid with
                             any other option.
        node (optional): A 48-bit Host ID. Only valid for version 1 (where it
                         is optional).
        clock_seq (optional): An integer of up to 14-bits for the sequence
                              number. Only valid for version 1 (where it is
                              optional).
        namespace: A namespace identifier, which is also a UUID. Required for
                   versions 3 and 5, must be omitted otherwise.
        name: string, required for versions 3 and 5, must be omitted otherwise.
        version: Version of UUID to use (1, 3, 4 or 5). If omitted, attempts to
                 guess which version to generate, defaulting to version 4
                 (totally random).

    Raises:
        ValueError: on invalid constructor arguments
    """
    # This was originally scapy.contrib.dce_rpc.RandUUID.

    _BASE = "([0-9a-f]{{{0}}}|\\*|[0-9a-f]{{{0}}}:[0-9a-f]{{{0}}})"
    _REG = re.compile(
        r"^{0}-?{1}-?{1}-?{2}{2}-?{2}{2}{2}{2}{2}{2}$".format(
            _BASE.format(8), _BASE.format(4), _BASE.format(2)
        ),
        re.I
    )
    VERSIONS = [1, 3, 4, 5]

    def __init__(self,
                 template=None,  # type: Optional[Any]
                 node=None,  # type: Optional[int]
                 clock_seq=None,  # type: Optional[int]
                 namespace=None,  # type: Optional[uuid.UUID]
                 name=None,  # type: Optional[str]
                 version=None,  # type: Optional[Any]
                 ):
        # type: (...) -> None
        self._template = template
        self._ori_version = version

        self.uuid_template = None
        self.clock_seq = None
        self.namespace = None
        self.name = None
        self.node = None
        self.version = None

        if template:
            if node or clock_seq or namespace or name or version:
                raise ValueError("UUID template must be the only parameter, "
                                 "if specified")
            tmp = RandUUID._REG.match(template)
            if tmp:
                template = tmp.groups()
            else:
                # Invalid template
                raise ValueError("UUID template is invalid")
            rnd_f = [RandInt] + [RandShort] * 2 + [RandByte] * 8  # type: ignore  # noqa: E501
            uuid_template = []  # type: List[Union[int, RandNum]]
            for i, t in enumerate(template):
                if t == "*":
                    uuid_template.append(rnd_f[i]())
                elif ":" in t:
                    mini, maxi = t.split(":")
                    uuid_template.append(
                        RandNum(int(mini, 16), int(maxi, 16))
                    )
                else:
                    uuid_template.append(int(t, 16))

            self.uuid_template = tuple(uuid_template)
        else:
            if version:
                if version not in RandUUID.VERSIONS:
                    raise ValueError("version is not supported")
                else:
                    self.version = version
            else:
                # No version specified, try to guess...
                # This could be wrong, and cause an error later!
                if node or clock_seq:
                    self.version = 1
                elif namespace and name:
                    self.version = 5
                else:
                    # Don't know, random!
                    self.version = 4

            # We have a version, now do things...
            if self.version == 1:
                if namespace or name:
                    raise ValueError("namespace and name may not be used with "
                                     "version 1")
                self.node = node
                self.clock_seq = clock_seq
            elif self.version in (3, 5):
                if node or clock_seq:
                    raise ValueError("node and clock_seq may not be used with "
                                     "version {}".format(self.version))

                self.namespace = namespace
                self.name = name
            elif self.version == 4:
                if namespace or name or node or clock_seq:
                    raise ValueError("node, clock_seq, node and clock_seq may "
                                     "not be used with version 4. If you "
                                     "did not specify version, you need to "
                                     "specify it explicitly.")

    def _command_args(self):
        # type: () -> str
        ret = []
        if self._template:
            ret.append("template=%r" % self._template)
        if self.node:
            ret.append("node=%r" % self.node)
        if self.clock_seq:
            ret.append("clock_seq=%r" % self.clock_seq)
        if self.namespace:
            ret.append("namespace=%r" % self.namespace)
        if self.name:
            ret.append("name=%r" % self.name)
        if self._ori_version:
            ret.append("version=%r" % self._ori_version)
        return ", ".join(ret)

    def _fix(self):
        # type: () -> uuid.UUID
        if self.uuid_template:
            return uuid.UUID(("%08x%04x%04x" + ("%02x" * 8))
                             % self.uuid_template)
        elif self.version == 1:
            return uuid.uuid1(self.node, self.clock_seq)
        elif self.version == 3:
            if not self.namespace or not self.name:
                raise ValueError("Missing namespace or name")
            return uuid.uuid3(self.namespace, self.name)
        elif self.version == 4:
            return uuid.uuid4()
        elif self.version == 5:
            if not self.namespace or not self.name:
                raise ValueError("Missing namespace or name")
            return uuid.uuid5(self.namespace, self.name)
        else:
            raise ValueError("Unhandled version") class VolatileValue(Generic[_T]):
    def __repr__(self):
        # type: () -> str
        return "<%s>" % self.__class__.__name__

    def _command_args(self):
        # type: () -> str
        return ''

    def command(self):
        # type: () -> str
        return "%s(%s)" % (self.__class__.__name__, self._command_args())

    def __eq__(self, other):
        # type: (Any) -> bool
        x = self._fix()
        y = other._fix() if isinstance(other, VolatileValue) else other
        if not isinstance(x, type(y)):
            return False
        return bool(x == y)

    def __ne__(self, other):
        # type: (Any) -> bool
        # Python 2.7 compat
        return not self == other

    __hash__ = None  # type: ignore

    def __getattr__(self, attr):
        # type: (str) -> Any
        if attr in ["__setstate__", "__getstate__"]:
            raise AttributeError(attr)
        return getattr(self._fix(), attr)

    def __str__(self):
        # type: () -> str
        return str(self._fix())

    def __bytes__(self):
        # type: () -> bytes
        return bytes_encode(self._fix())

    def __len__(self):
        # type: () -> int
        # Does not work for some types (int?)
        return len(self._fix())  # type: ignore

    def copy(self):
        # type: () -> Any
        return copy.copy(self)

    def _fix(self):
        # type: () -> _T
        return cast(_T, None) class RandSShort(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, -2**15, 2**15 - 1) class RandSLong(RandNum):
    def __init__(self):
        # type: () -> None
        RandNum.__init__(self, -2**63, 2**63 - 1) class RandFloat(_RandNumeral[float]):
    def __init__(self, min, max):
        # type: (int, int) -> None
        self.min = min
        self.max = max

    def _fix(self):
        # type: () -> float
        return random.uniform(self.min, self.max) def bytes_hex(x):
    # type: (AnyStr) -> bytes
    """Hexify a str or a bytes object"""
    return binascii.b2a_hex(bytes_encode(x)) def chb(x):
    # type: (int) -> bytes
    if isinstance(x, str):
        return x
    return chr(x) def orb(x):
    # type: (Union[int, str, bytes]) -> int
    """Return ord(x) when not already an int."""
    if isinstance(x, int):
        return x
    return ord(x) def plain_str(x):
    # type: (AnyStr) -> str
    """Convert basic byte objects to str"""
    if isinstance(x, bytes):
        return x.decode(errors="ignore")
    return str(x) def raw(x):
    # type: (Union[Packet]) -> bytes
    """
    Builds a packet and returns its bytes representation.
    This function is and will always be cross-version compatible
    """
    if hasattr(x, "__bytes__"):
        return x.__bytes__()
    return bytes(x) def bytes_encode(x):
    # type: (Any) -> bytes
    """Ensure that the given object is bytes.
    If the parameter is a packet, raw() should be preferred.
    """
    if isinstance(x, str):
        return x.encode()
    return bytes(x) def issubtype(x,  # type: Any
              t,  # type: Union[type, str]
              ):
    def __add__(self, other, context=None):
    def __radd__(self, other):
    def __sub__(self, other):
    def __rsub__(self, other):
    def __mul__(self, other):
    def __rmul__(self, other):
    def __truediv__(self, other):
    def __floordiv__(self, other):
        def __divmod__(self, other):
        def __div__(self, other):
        def __rdiv__(self, other):
    def __mod__(self, other):
    def __rmod__(self, other):
    def __pow__(self, other, modulo=None):
    def __eq__(self, other):
    def normalize(self, precision):  # type: ignore
def get_temp_file(keep, autoext, fd):
def get_temp_file(keep=False, autoext="", fd=False):  # noqa: F811
def get_temp_file(keep=False, autoext="", fd=False):  # noqa: F811
def get_temp_dir(keep=False):
def sane(x, color=False):
def restart():
def lhex(x):
def hexdump(p, dump=False):
def linehexdump(p, onlyasc=0, onlyhex=0, dump=False):
def chexdump(p, dump=False):
def hexstr(p, onlyasc=0, onlyhex=0, color=False):
def repr_hex(s):
def hexdiff(a, b, autojunk=False):
def checksum(pkt):
def _fletcher16(charbuf):
def fletcher16_checksum(binbuf):
def fletcher16_checkbytes(binbuf, offset):
def mac2str(mac):
def valid_mac(mac):
def str2mac(s):
def randstring(length):
def zerofree_randstring(length):
def strxor(s1, s2):
def strand(s1, s2):
    def inet_aton(ip_string):
def atol(x):
def valid_ip(addr):
def valid_net(addr):
def valid_ip6(addr):
def valid_net6(addr):
def ltoa(x):
def itom(x):
    def __init__(self, prog, suppress=True):
    def __enter__(self):
    def __exit__(self,
                 exc_type,  # type: Optional[type]
                 exc_value,  # type: Optional[Exception]
                 traceback,  # type: Optional[Any]
                 ):
    def __init__(self):
    def __enter__(self):
        def write(s, decorator=self):
    def __exit__(self, *exc):
    def get_output(self, eval_bytes=False):
def do_graph(
    graph,  # type: str
    prog=None,  # type: Optional[str]
    format=None,  # type: Optional[str]
    target=None,  # type: Optional[Union[IO[bytes], str]]
    type=None,  # type: Optional[str]
    string=None,  # type: Optional[bool]
    options=None  # type: Optional[List[str]]
):
def tex_escape(x):
def colgen(*lstcol,  # type: Any
           **kargs  # type: Any
           ):
def incremental_label(label="tag%05i", start=0):
def binrepr(val):
def long_converter(s):
    def __init__(self, key, value):
    def __repr__(self):
    def __getattr__(self, attr):
    def __str__(self):
    def __bytes__(self):
    def __hash__(self):
    def __int__(self):
    def __eq__(self, other):
    def __neq__(self, other):
    def __new__(cls, name, bases, dct):
    def __getitem__(self, attr):
    def __contains__(self, val):
    def get(self, attr, val=None):
    def __repr__(self):
def export_object(obj):
def import_object(obj=None):
def save_object(fname, obj):
def load_object(fname):
def corrupt_bytes(data, p=0.01, n=None):
def corrupt_bits(data, p=0.01, n=None):
def wrpcap(filename,  # type: Union[IO[bytes], str]
           pkt,  # type: _PacketIterable
           *args,  # type: Any
           **kargs  # type: Any
           ):
def rdpcap(filename, count=-1):
    def __new__(cls, name, bases, dct):
    def __call__(cls, filename):  # type: ignore
    def open(fname  # type: Union[IO[bytes], str]
             ):
    def __init__(self, filename, fdesc=None, magic=None):  # type: ignore
    def __iter__(self):
    def next(self):
    def __next__(self):
    def _read_packet(self, size=MTU):
    def read_packet(self, size=MTU):
    def dispatch(self,
                 callback  # type: Callable[[Tuple[bytes, RawPcapReader.PacketMetadata]], Any]  # noqa: E501
                 ):
    def _read_all(self, count=-1):
    def recv(self, size=MTU):
    def fileno(self):
    def close(self):
    def __exit__(self, exc_type, exc_value, tracback):
    def select(sockets,  # type: List[SuperSocket]
               remain=None,  # type: Optional[float]
               ):
    def __init__(self, filename, fdesc=None, magic=None):  # type: ignore
    def __enter__(self):
    def read_packet(self, size=MTU):
    def recv(self, size=MTU):
    def next(self):
    def read_all(self, count=-1):
    def __init__(self, filename, fdesc=None, magic=None):  # type: ignore
    def _read_block(self, size=MTU):
    def _read_block_tail(self, blocklen):
    def _read_block_shb(self):
    def _read_packet(self, size=MTU):  # type: ignore
    def _read_options(self, options):
    def _read_block_idb(self, block, _):
    def _check_interface_id(self, intid):
    def _read_block_epb(self, block, size):
    def _read_block_spb(self, block, size):
    def _read_block_pkt(self, block, size):
    def _read_block_dsb(self, block, size):
    def __init__(self, filename, fdesc=None, magic=None):  # type: ignore
    def __enter__(self):
    def read_packet(self, size=MTU):
    def recv(self, size=MTU):
    def __init__(self,
                 filename,  # type: Union[IO[bytes], str]
                 linktype=None,  # type: Optional[int]
                 gz=False,  # type: bool
                 endianness="",  # type: str
                 append=False,  # type: bool
                 sync=False,  # type: bool
                 nano=False,  # type: bool
                 snaplen=MTU,  # type: int
                 ):
    def fileno(self):
    def write_header(self, pkt):
    def _write_header(self, pkt):
    def write(self, pkt):
    def write_packet(self,
                     packet,  # type: Union[bytes, Packet]
                     sec=None,  # type: Optional[int]
                     usec=None,  # type: Optional[int]
                     caplen=None,  # type: Optional[int]
                     wirelen=None,  # type: Optional[int]
                     ):
    def _write_packet(self,
                      packet,  # type: bytes
                      sec=None,  # type: Optional[int]
                      usec=None,  # type: Optional[int]
                      caplen=None,  # type: Optional[int]
                      wirelen=None  # type: Optional[int]
                      ):
    def flush(self):
    def close(self):
    def __enter__(self):
    def __exit__(self, exc_type, exc_value, tracback):
    def write_header(self, pkt):
    def write_packet(self,
                     packet,  # type: Union[bytes, Packet]
                     sec=None,  # type: Optional[int]
                     usec=None,  # type: Optional[int]
                     caplen=None,  # type: Optional[int]
                     wirelen=None,  # type: Optional[int]
                     ):
def import_hexcap(input_string=None):
def wireshark(pktlist, wait=False, **kwargs):
def tdecode(
    pktlist,  # type: Union[IO[bytes], None, str, _PacketIterable]
    args=None,  # type: Optional[List[str]]
    **kwargs  # type: Any
):
def _guess_linktype_name(value):
def _guess_linktype_value(name):
def tcpdump(
    pktlist=None,  # type: Union[IO[bytes], None, str, _PacketIterable]
    dump=False,  # type: bool
    getfd=False,  # type: bool
    args=None,  # type: Optional[List[str]]
    flt=None,  # type: Optional[str]
    prog=None,  # type: Optional[Any]
    getproc=False,  # type: bool
    quiet=False,  # type: bool
    use_tempfile=None,  # type: Optional[Any]
    read_stdin_opts=None,  # type: Optional[Any]
    linktype=None,  # type: Optional[Any]
    wait=True,  # type: bool
    _suppress=False  # type: bool
):
def hexedit(pktlist):
def get_terminal_width():
def pretty_list(rtlst,  # type: List[Tuple[Union[str, List[str]], ...]]
                header,  # type: List[Tuple[str, ...]]
                sortBy=0,  # type: int
                borders=False,  # type: bool
                ):
def __make_table(
    yfmtfunc,  # type: Callable[[int], str]
    fmtfunc,  # type: Callable[[int], str]
    endline,  # type: str
    data,  # type: List[Tuple[Packet, Packet]]
    fxyz,  # type: Callable[[Packet, Packet], Tuple[Any, Any, Any]]
    sortx=None,  # type: Optional[Callable[[str], Tuple[Any, ...]]]
    sorty=None,  # type: Optional[Callable[[str], Tuple[Any, ...]]]
    seplinefunc=None,  # type: Optional[Callable[[int, List[int]], str]]
    dump=False  # type: bool
):
def make_table(*args, **kargs):
def make_lined_table(*args, **kargs):
def make_tex_table(*args, **kargs):
def whois(ip_address):
    def __init__(self, sock, pkt, interval=0.5):
    def run(self):
    def stop(self):
    def __init__(self, o):
    def __dict__(self):  # type: ignore
    def __getattr__(self, name):
    def sr1(self, *args, **kargs):
    def sr(self, *args, **kargs):
    def send(self, x):
class EDecimal(Decimal):
class ContextManagerSubprocess(object):
class ContextManagerCaptureOutput(object):
class EnumElement:
class Enum_metaclass(type):
class PcapReader_metaclass(type):
class RawPcapReader:
class PcapReader(RawPcapReader, _SuperSocket):
class RawPcapNgReader(RawPcapReader):
class PcapNgReader(RawPcapNgReader, PcapReader, _SuperSocket):
class RawPcapWriter:
class PcapWriter(RawPcapWriter):
class PeriodicSenderThread(threading.Thread):
class SingleConversationSocket(object):
_TEX_TR = {
    "{": "{\\tt\\char123}",
    "}": "{\\tt\\char125}",
    "\\": "{\\tt\\char92}",
    "^": "\\^{}",
    "$": "\\$",
    "#": "\\#",
    "_": "\\_",
    "&": "\\&",
    "%": "\\%",
    "|": "{\\tt\\char124}",
    "~": "{\\tt\\char126}",
    "<": "{\\tt\\char60}",
    ">": "{\\tt\\char62}",
} def in6_6to4ExtractAddr(addr):
    # type: (str) -> Optional[str]
    """
    Extract IPv4 address embedded in 6to4 address. Passed address must be
    a 6to4 address. None is returned on error.
    """
    try:
        baddr = inet_pton(socket.AF_INET6, addr)
    except Exception:
        return None
    if baddr[:2] != b" \x02":
        return None
    return inet_ntop(socket.AF_INET, baddr[2:6]) def in6_isaddr6to4(x):
    # type: (str) -> bool
    """
    Return True if provided address (in printable format) is a 6to4
    address (being in 2002::/16).
    """
    bx = inet_pton(socket.AF_INET6, x)
    return bx[:2] == b' \x02' def in6_isaddrTeredo(x):
    # type: (str) -> bool
    """
    Return True if provided address is a Teredo, meaning it is under
    the /32 conf.teredoPrefix prefix value (by default, 2001::).
    Otherwise, False is returned. Address must be passed in printable
    format.
    """
    our = inet_pton(socket.AF_INET6, x)[0:4]
    teredoPrefix = inet_pton(socket.AF_INET6, conf.teredoPrefix)[0:4]
    return teredoPrefix == our def in6_ptop(str):
    # type: (str) -> str
    """
    Normalizes IPv6 addresses provided in printable format, returning the
    same address in printable format. (2001:0db8:0:0::1 -> 2001:db8::1)
    """
    return inet_ntop(socket.AF_INET6, inet_pton(socket.AF_INET6, str)) class Net6(Net):  # syntax ex. 2011:db8::/126
    """Network object from an IP address or hostname and mask"""
    name = "Net6"  # type: str
    family = socket.AF_INET6  # type: int
    max_mask = 128  # type: int

    @classmethod
    def ip2int(cls, addr):
        # type: (str) -> int
        val1, val2 = struct.unpack(
            '!QQ', inet_pton(socket.AF_INET6, cls.name2addr(addr))
        )
        return cast(int, (val1 << 64) + val2)

    @staticmethod
    def int2ip(val):
        # type: (int) -> str
        return inet_ntop(
            socket.AF_INET6,
            struct.pack('!QQ', val >> 64, val & 0xffffffffffffffff),
        ) def teredoAddrExtractInfo(x):
    # type: (str) -> Tuple[str, int, str, int]
    """
    Extract information from a Teredo address. Return value is
    a 4-tuple made of IPv4 address of Teredo server, flag value (int),
    mapped address (non obfuscated) and mapped port (non obfuscated).
    No specific checks are performed on passed address.
    """
    addr = inet_pton(socket.AF_INET6, x)
    server = inet_ntop(socket.AF_INET, addr[4:8])
    flag = struct.unpack("!H", addr[8:10])[0]  # type: int
    mappedport = struct.unpack("!H", strxor(addr[10:12], b'\xff' * 2))[0]
    mappedaddr = inet_ntop(socket.AF_INET, strxor(addr[12:16], b'\xff' * 4))
    return server, flag, mappedaddr, mappedport class Gen(Generic[_T]):
    __slots__ = []  # type: List[str]

    def __iter__(self):
        # type: () -> Iterator[_T]
        return iter([])

    def __iterlen__(self):
        # type: () -> int
        return sum(1 for _ in iter(self)) class Net(Gen[str]):
    """Network object from an IP address or hostname and mask"""
    name = "Net"  # type: str
    family = socket.AF_INET  # type: int
    max_mask = 32  # type: int

    @classmethod
    def name2addr(cls, name):
        # type: (str) -> str
        try:
            return next(
                addr_port[0]
                for family, _, _, _, addr_port in
                socket.getaddrinfo(name, None, cls.family)
                if family == cls.family
            )
        except socket.error:
            if re.search("(^|\\.)[0-9]+-[0-9]+($|\\.)", name) is not None:
                raise Scapy_Exception("Ranges are no longer accepted in %s()" %
                                      cls.__name__)
            raise

    @classmethod
    def ip2int(cls, addr):
        # type: (str) -> int
        return cast(int, struct.unpack(
            "!I", socket.inet_aton(cls.name2addr(addr))
        )[0])

    @staticmethod
    def int2ip(val):
        # type: (int) -> str
        return socket.inet_ntoa(struct.pack('!I', val))

    def __init__(self, net, stop=None):
        # type: (str, Union[None, str]) -> None
        if "*" in net:
            raise Scapy_Exception("Wildcards are no longer accepted in %s()" %
                                  self.__class__.__name__)
        if stop is None:
            try:
                net, mask = net.split("/", 1)
            except ValueError:
                self.mask = self.max_mask  # type: Union[None, int]
            else:
                self.mask = int(mask)
            self.net = net  # type: Union[None, str]
            inv_mask = self.max_mask - self.mask
            self.start = self.ip2int(net) >> inv_mask << inv_mask
            self.count = 1 << inv_mask
            self.stop = self.start + self.count - 1
        else:
            self.start = self.ip2int(net)
            self.stop = self.ip2int(stop)
            self.count = self.stop - self.start + 1
            self.net = self.mask = None

    def __str__(self):
        # type: () -> str
        return next(iter(self), "")

    def __iter__(self):
        # type: () -> Iterator[str]
        # Python 2 won't handle huge (> sys.maxint) values in range()
        for i in range(self.count):
            yield self.int2ip(self.start + i)

    def __len__(self):
        # type: () -> int
        return self.count

    def __iterlen__(self):
        # type: () -> int
        # for compatibility
        return len(self)

    def choice(self):
        # type: () -> str
        return self.int2ip(random.randint(self.start, self.stop))

    def __repr__(self):
        # type: () -> str
        if self.mask is not None:
            return '%s("%s/%d")' % (
                self.__class__.__name__,
                self.net,
                self.mask,
            )
        return '%s("%s", "%s")' % (
            self.__class__.__name__,
            self.int2ip(self.start),
            self.int2ip(self.stop),
        )

    def __eq__(self, other):
        # type: (Any) -> bool
        if isinstance(other, str):
            return self == self.__class__(other)
        if not isinstance(other, Net):
            return False
        if self.family != other.family:
            return False
        return (self.start == other.start) and (self.stop == other.stop)

    def __ne__(self, other):
        # type: (Any) -> bool
        # Python 2.7 compat
        return not self == other

    def __hash__(self):
        # type: () -> int
        return hash(("scapy.Net", self.family, self.start, self.stop))

    def __contains__(self, other):
        # type: (Any) -> bool
        if isinstance(other, int):
            return self.start <= other <= self.stop
        if isinstance(other, str):
            return self.__class__(other) in self
        if type(other) is not self.__class__:
            return False
        return self.start <= other.start <= other.stop <= self.stop class BasePacket(Gen['scapy.packet.Packet']):
    __slots__ = []  # type: List[str] class Field_metaclass(_Generic_metaclass):
    def __new__(cls,
                name,  # type: str
                bases,  # type: Tuple[type, ...]
                dct  # type: Dict[str, Any]
                ):
        # type: (...) -> Type[scapy.fields.Field[Any, Any]]
        dct.setdefault("__slots__", [])
        newcls = super(Field_metaclass, cls).__new__(cls, name, bases, dct)
        return newcls  # type: ignore     FAKE_TYPING = False
    FAKE_TYPING = True
    TYPE_CHECKING = False
    IO = _FakeType("IO")  # type: ignore
        AF_INET = socket.AF_INET
        AF_INET6 = socket.AF_INET6
class _Generic_metaclass(type):
    class _FT(object):
    class Sized(object):  # type: ignore
    class Generic(object):  # type: ignore
        class _NT(cls):
    class AddressFamily:
        def __getitem__(self, typ):
def _FakeType(name, cls=object):
        def __init__(self, name):
        def __getitem__(self, item):  # type: ignore
        def __call__(self, *args, **kargs):
        def __repr__(self):
    def cast(_type, obj):  # type: ignore
    def _unpickleNamedTuple(name, len_params, *args):
    def NamedTuple(name, params):
            def __reduce__(self):
def lambda_tuple_converter(func):
    def chb(x):
    def raw(x):
    def raw(x):
    def bytes_encode(x):
        def plain_str(x):
        def plain_str(x):
    def chb(x):
    def orb(x):
def bytes_hex(x):
def hex_bytes(x):
    def int_bytes(x, size):
    def bytes_int(x):
    def int_bytes(x, size):
    def bytes_int(x):
def base64_bytes(x):
def bytes_base64(x):
    def gzip_decompress(x):
    def gzip_compress(x):
import calendar
import collections
import copy
import inspect
import math
import socket
import struct
import time
import warnings
import scapy.modules.six as six
            import scapy.route  # noqa: F401
                import scapy.route6  # noqa: F401
from types import MethodType
from uuid import UUID
from scapy.config import conf
from scapy.dadict import DADict
from scapy.volatile import RandBin, RandByte, RandEnumKeys, RandInt, \
    RandIP, RandIP6, RandLong, RandMAC, RandNum, RandShort, RandSInt, \
    RandSByte, RandTermString, RandUUID, VolatileValue, RandSShort, \
    RandSLong, RandFloat
from scapy.data import EPOCH
from scapy.error import log_runtime, Scapy_Exception
from scapy.compat import bytes_hex, chb, orb, plain_str, raw, bytes_encode
from scapy.pton_ntop import inet_ntop, inet_pton
from scapy.utils import inet_aton, inet_ntoa, lhex, mac2str, str2mac, EDecimal
from scapy.utils6 import in6_6to4ExtractAddr, in6_isaddr6to4, \
    in6_isaddrTeredo, in6_ptop, Net6, teredoAddrExtractInfo
from scapy.base_classes import Gen, Net, BasePacket, Field_metaclass
from scapy.error import warning
from scapy.modules.six import integer_types
from scapy.compat import (
    Any,
    AnyStr,
    Callable,
    Dict,
    List,
    Generic,
    Optional,
    Set,
    Tuple,
    Type,
    TypeVar,
    Union,
    # func
    cast,
    TYPE_CHECKING,
)
    from scapy.packet import Packet
        from scapy.packet import fuzz

    def randval(self):
        # type: () -> RandIP
        return RandIP()


class SourceIPField(IPField):
    __slots__ = ["dstname"]

    def __init__(self, name, dstname):
        # type: (str, Optional[str]) -> None
        IPField.__init__(self, name, None)
        self.dstname = dstname

    def __findaddr(self, pkt):
        # type: (Packet) -> str
        if conf.route is None:
            # unused import, only to initialize conf.route
        dst = ("0.0.0.0" if self.dstname is None
               else getattr(pkt, self.dstname) or "0.0.0.0")
        if isinstance(dst, (Gen, list)):
            r = {
                conf.route.route(str(daddr))
                for daddr in dst
            }  # type:  Set[Tuple[str, str, str]]
            if len(r) > 1:
                warning("More than one possible route for %r" % (dst,))
            return min(r)[1]
        return conf.route.route(dst)[1]

    def i2m(self, pkt, x):
        # type: (Optional[Packet], Optional[Union[str, Net]]) -> bytes
        if x is None and pkt is not None:
            x = self.__findaddr(pkt)
        return super(SourceIPField, self).i2m(pkt, x)

    def i2h(self, pkt, x):
        # type: (Optional[Packet], Optional[Union[str, Net]]) -> str
        if x is None and pkt is not None:
            x = self.__findaddr(pkt)
        return super(SourceIPField, self).i2h(pkt, x)


class IP6Field(Field[Optional[Union[str, Net6]], bytes]):
    def __init__(self, name, default):
        # type: (str, Optional[str]) -> None
        Field.__init__(self, name, default, "16s")

    def h2i(self, pkt, x):
        # type: (Optional[Packet], Optional[str]) -> str
        if isinstance(x, bytes):
            x = plain_str(x)
        if isinstance(x, str):
            try:
                x = in6_ptop(x)
            except socket.error:
                return Net6(x)  # type: ignore
        elif isinstance(x, list):
            x = [self.h2i(pkt, n) for n in x]
        return x  # type: ignore

    def i2h(self, pkt, x):
        # type: (Optional[Packet], Optional[Union[str, Net6]]) -> str
        return cast(str, x)

    def i2m(self, pkt, x):
        # type: (Optional[Packet], Optional[Union[str, Net6]]) -> bytes
        if x is None:
            x = "::"
        return inet_pton(socket.AF_INET6, plain_str(x))

    def m2i(self, pkt, x):
        # type: (Optional[Packet], bytes) -> str
        return inet_ntop(socket.AF_INET6, x)

    def any2i(self, pkt, x):
        # type: (Optional[Packet], Optional[str]) -> str
        return self.h2i(pkt, x)

    def i2repr(self, pkt, x):
        # type: (Optional[Packet], Optional[Union[str, Net6]]) -> str
        if x is None:
            return self.i2h(pkt, x)
        elif not isinstance(x, Net6) and not isinstance(x, list):
            if in6_isaddrTeredo(x):   # print Teredo info
                server, _, maddr, mport = teredoAddrExtractInfo(x)
                return "%s [Teredo srv: %s cli: %s:%s]" % (self.i2h(pkt, x), server, maddr, mport)  # noqa: E501
            elif in6_isaddr6to4(x):   # print encapsulated address
                vaddr = in6_6to4ExtractAddr(x)
                return "%s [6to4 GW: %s]" % (self.i2h(pkt, x), vaddr)
        r = self.i2h(pkt, x)          # No specific information to return
        return r if isinstance(r, str) else repr(r)

    def randval(self):
        # type: () -> RandIP6
        return RandIP6()


class SourceIP6Field(IP6Field):
    __slots__ = ["dstname"]

    def __init__(self, name, dstname):
        # type: (str, str) -> None
        IP6Field.__init__(self, name, None)
        self.dstname = dstname

    def i2m(self, pkt, x):
        # type: (Optional[Packet], Optional[Union[str, Net6]]) -> bytes
        if x is None:
            dst = ("::" if self.dstname is None else
                   getattr(pkt, self.dstname) or "::")
            iff, x, nh = conf.route6.route(dst)
        return super(SourceIP6Field, self).i2m(pkt, x)

    def i2h(self, pkt, x):
        # type: (Optional[Packet], Optional[Union[str, Net6]]) -> str
        if x is None:
            if conf.route6 is None:
                # unused import, only to initialize conf.route6
            dst = ("::" if self.dstname is None else getattr(pkt, self.dstname))  # noqa: E501

            if isinstance(dst, (Gen, list)):