open_pcap: Windows routine for creating a pcap from an interface.
    This function is also responsible for detecting monitor mode.
195977
def open_pcap(iface, *args, **kargs):
    
    iface_pcap_name = pcapname(iface)
    if not isinstance(iface, NetworkInterface) and iface_pcap_name is not None:
        iface = IFACES.dev_from_name(iface)
    if iface.is_invalid():
        raise Scapy_Exception("Interface is invalid (no pcap match found) !")
    # Only check monitor mode when manually specified.
    # Checking/setting for monitor mode will slow down the process, and the
    # common is case is not to use monitor mode
    kw_monitor = kargs.get("monitor", None)
    if conf.use_npcap and kw_monitor is not None and iface is not None:
        monitored = iface.ismonitor()
        if kw_monitor is not monitored:
            # The monitor param is specified, and not matching the current
            # interface state
            iface.setmonitor(kw_monitor)
    return _orig_open_pcap(iface_pcap_name, *args, **kargs)
541064
def _scapy_read_frame(self):
        """"""
        from pcapkit.toolkit.scapy import (ipv4_reassembly, ipv6_reassembly,
                                           packet2chain, packet2dict, tcp_reassembly,
                                           tcp_traceflow)

        # fetch Scapy packet
        packet = next(self._extmp)

        # verbose output
        self._frnum += 1
        self._proto = packet2chain(packet)
        if self._flag_v:
            print(f' - Frame {self._frnum:>3d}: {self._proto}')

        # write plist
        frnum = f'Frame {self._frnum}'
        if not self._flag_q:
            info = packet2dict(packet)
            if self._flag_f:
                ofile = self._ofile(f'{self._ofnm}/{frnum}.{self._fext}')
                ofile(info, name=frnum)
            else:
                self._ofile(info, name=frnum)

        # record frames
        if self._flag_d:
            # setattr(packet, 'packet2dict', packet2dict)
            # setattr(packet, 'packet2chain', packet2chain)
            self._frame.append(packet)

        # record fragments
        if self._ipv4:
            flag, data = ipv4_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[0](data)  # pylint: disable=E1102
        if self._ipv6:
            flag, data = ipv6_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[1](data)  # pylint: disable=E1102
        if self._tcp:
            flag, data = tcp_reassembly(packet, count=self._frnum)
            if flag:
                self._reasm[2](data)  # pylint: disable=E1102

        # trace flows
        if self._flag_t:
            flag, data = tcp_traceflow(packet, count=self._frnum)
            if flag:
                self._trace(data)

        return packet
863278
def _port_op(op_name, port, protocol="TCP"):
    """"""
    _args = [op_name]
    icmp = protocol.upper() == "ICMP"
    if icmp:
        _args.append(protocol)
    else:
        _args.append('{}/{}'.format(port, protocol))
    try:
        subprocess.check_call(_args)
    except subprocess.CalledProcessError:
        # Older Juju pre 2.3 doesn't support ICMP
        # so treat it as a no-op if it fails.
        if not icmp:
            raise
1368462
def _pcap_check(cls):
        """"""
        if not conf.use_winpcapy:
            # Winpcap/Npcap isn't installed
            return

        _detect = pcap_service_status()

        def _ask_user():
            if not conf.interactive:
                return False
            msg = "Do you want to start it ? (yes/no) [y]: "
            try:
                # Better IPython compatibility
                import IPython
                return IPython.utils.io.ask_yes_no(msg, default='y')
            except (NameError, ImportError):
                while True:
                    _confir = input(msg)
                    _confir = _confir.lower().strip()
                    if _confir in ["yes", "y", ""]:
                        return True
                    elif _confir in ["no", "n"]:
                        return False
                return False
        _error_msg = ("No match between your pcap and windows "
                      "network interfaces found. ")
        if _detect:
            # No action needed
            return
        else:
            warning(
                "Scapy has detected that your pcap service is not running !"
            )
            if not conf.interactive or _ask_user():
                succeed = pcap_service_start(askadmin=conf.interactive)
                if succeed:
                    log_loading.info("Pcap service started !")
                    return
            _error_msg = "Could not start the pcap service ! "
        warning(_error_msg +
                "You probably won't be able to send packets. "
                "Deactivating unneeded interfaces and restarting "
                "Scapy might help. Check your winpcap/npcap installation "
                "and access rights.")
16299
def Open(self, file_object):
    
    file_object.seek(0, os.SEEK_SET)
    signature_data = file_object.read(6)

    self.file_format = None
    if len(signature_data) > 2:
      if signature_data[:2] == self._CPIO_SIGNATURE_BINARY_BIG_ENDIAN:
        self.file_format = 'bin-big-endian'
      elif signature_data[:2] == self._CPIO_SIGNATURE_BINARY_LITTLE_ENDIAN:
        self.file_format = 'bin-little-endian'
      elif signature_data == self._CPIO_SIGNATURE_PORTABLE_ASCII:
        self.file_format = 'odc'
      elif signature_data == self._CPIO_SIGNATURE_NEW_ASCII:
        self.file_format = 'newc'
      elif signature_data == self._CPIO_SIGNATURE_NEW_ASCII_WITH_CHECKSUM:
        self.file_format = 'crc'

    if self.file_format is None:
      raise IOError('Unsupported CPIO format.')

    self._file_object = file_object
    self._file_size = file_object.get_size()

    self._ReadFileEntries(self._file_object)
1167533
def openSource(p, filetype=None):
    ''
    if not filetype:
        filetype = options.filetype
    if isinstance(p, str):
        if '://' in p:
            return openSource(UrlPath(p), filetype)  # convert to Path and recurse
        elif p == '-':
            return openSource(PathFd('-', vd().stdin), filetype)
        else:
            return openSource(Path(p), filetype)  # convert to Path and recurse
    elif isinstance(p, UrlPath):
        openfunc = 'openurl_' + p.scheme
        return getGlobals()[openfunc](p, filetype=filetype)
    elif isinstance(p, Path):
        if not filetype:
            filetype = p.suffix or 'txt'

        if os.path.isdir(p.resolve()):
            filetype = 'dir'

        openfunc = 'open_' + filetype.lower()
        if openfunc not in getGlobals():
            warning('no %s function' % openfunc)
            filetype = 'txt'
            openfunc = 'open_txt'
        vs = getGlobals()[openfunc](p)
    else:  # some other object
        status('unknown object type %s' % type(p))
        vs = None

    if vs:
        status('opening %s as %s' % (p.name, filetype))

    return vs
218707
public static void main(String[] args) throws InterruptedException {
        StringBuilder errbuf = new StringBuilder();
        try {
            PcapIf pcapIf = pcapIf(errbuf);
            Pcap.Builder builder = new Pcap.Builder()
                    .source(pcapIf.getName())
                    .snaplen(SNAPLEN)
                    .promiscuousMode(PROMISCUOUS)
                    .timeout(TIMEOUT)
                    .immediateMode(IMMEDIATE)
                    .timestampType(TIMESTAMP_TYPE)
                    .timestampPrecision(TIMESTAMP_PRECISION)
                    .rfmon(RFMON)
                    .enableNonBlock(nonBlock)
                    .dataLinkType(LINK_TYPE)
                    .fileName(FILE_NAME)
                    .errbuf(errbuf)
                    .pcapType(PCAP_TYPE);
            com.ardikars.jxnet.context.Application.run("application", "Application", "", builder);
            final Context context = com.ardikars.jxnet.context.Application.getApplicationContext();
            LOGGER.info("Network Interface : " + pcapIf.getName());
            LOGGER.info("Addresses         : ");
            for (PcapAddr addr : pcapIf.getAddresses()) {
                if (addr.getAddr().getSaFamily() == SockAddr.Family.AF_INET) {
                    LOGGER.info("\tAddress       : " + Inet4Address.valueOf(addr.getAddr().getData()));
                    LOGGER.info("\tNetwork       : " + Inet4Address.valueOf(addr.getNetmask().getData()));
                }
            }
            if (Platforms.isWindows()) {
                try {
                    byte[] hardwareAddress = Jxnet.FindHardwareAddress(pcapIf.getName());
                    LOGGER.info("\tMAC Address   : " + MacAddress.valueOf(hardwareAddress));
                } catch (PlatformNotSupportedException e) {
                    LOGGER.warning(e.getMessage());
                } catch (DeviceNotFoundException e) {
                    LOGGER.warning(e.getMessage());
                }
            } else {
                try {
                    LOGGER.info("\tMAC Address   : " + MacAddress.fromNicName(pcapIf.getName()));
                } catch (SocketException e) {
                    LOGGER.warning(e.getMessage());
                }
            }
            final ExecutorService pool = Executors.newCachedThreadPool();
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    pool.shutdownNow();
                }
            });

            final int linktype = context.pcapDataLink().getValue();

            context.pcapLoop(MAX_PACKET, new RawPcapHandler<String>() {

                @Override
                public void nextPacket(String user, int capLen, int len, int tvSec, long tvUsec, long memoryAddress) {
                    Memory buffer = Memories.wrap(memoryAddress, len);
                    buffer.writerIndex(buffer.capacity());
                    Packet packet;
                    if (linktype == 1) {
                        packet = Ethernet.newPacket(buffer);
                    } else {
                        packet = UnknownPacket.newPacket(buffer);
                    }
                    print(Tuple.of(PcapPktHdr.newInstance(capLen, len, tvSec, tvUsec), packet));
                }

            }, "Jxnet!", pool);
            pool.shutdown();
            pool.awaitTermination(WAIT_TIME_FOR_THREAD_TERMINATION, TimeUnit.MICROSECONDS);
        } catch (DeviceNotFoundException e) {
            LOGGER.warning(e.getMessage());
        }

    }
1026400
def _assemble_devinfo(self):
        '''
        
        '''
        devtype = {}
        for p in pcap_devices():
            if p.isloop:
                devtype[p.name] = InterfaceType.Loopback
            else:
                if sys.platform == 'linux':
                    st,output = subprocess.getstatusoutput(["iwconfig", p.name])
                    if "no wireless extensions" in output:
                        devtype[p.name] = InterfaceType.Wired
                    else:
                        devtype[p.name] = InterfaceType.Wireless
                elif sys.platform == 'darwin':
                    devtype[p.name] = InterfaceType.Unknown
                else:
                    devtype[p.name] = InterfaceType.Unknown

        devinfo = {}
        ifinfo = net_if_addrs()
        for devname in self._devs:
            ifaddrs = ifinfo.get(devname, None)
            if ifaddrs is None:
                log_warn("Address info for interface {} not found! (skipping)".format(devname))

            if sys.platform == 'darwin':
                layer2addrfam = socket.AddressFamily.AF_LINK
            elif sys.platform == 'linux':
                layer2addrfam = socket.AddressFamily.AF_PACKET
            else:
                raise RuntimeException("Platform not supported")

            macaddr = "00:00:00:00:00:00"
            ipaddr = mask = "0.0.0.0"
            for addrinfo in ifaddrs:
                if addrinfo.family == socket.AddressFamily.AF_INET:
                    ipaddr = IPv4Address(addrinfo.address)
                    mask = IPv4Address(addrinfo.netmask)
                elif addrinfo.family == layer2addrfam:
                    macaddr = EthAddr(addrinfo.address)

            ifnum = socket.if_nametoindex(devname)
            devinfo[devname] = Interface(devname, macaddr, ipaddr, netmask=mask, ifnum=ifnum, iftype=devtype[devname])
        return devinfo
113351
def create_connction(host, port, protocol):
    
    ai_list = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM)
    for (family, socktype, proto, canon, sockaddr) in ai_list:
        sock = socket.socket(family, socktype)
        # WRAP SOCKET
        if port == 443:
            sock = ssl.wrap_socket(sock, ssl_version=protocol)
        sock.connect(sockaddr)
        return sock
1072059
def open(self, url, mode='r', stdio=True):
        
        # doesn't need to use config, because the object is already created
        res = urlsplit(url)

        if not res.scheme:
            if not res.path or res.path == '-':
                if not stdio:
                    raise IOError("unable to open '%s'" % (url,))

                if 'w' in mode:
                    return sys.stdout
                return sys.stdin

            return open(res.path, mode)

        if res.scheme in ('https', 'http', 'ftp'):
            req = requests.get(res.geturl(), stream=True)
            # TODO error check
            return req.raw
            #return urllib2.urlopen(res.geturl())

        raise IOError("unable to open '%s'" % (url,))
480141
public static PcapIf pcapIf(StringBuilder errbuf) throws DeviceNotFoundException {
        String source = Application.source;
        List<PcapIf> alldevsp = new ArrayList<PcapIf>();
        if (PcapFindAllDevs(alldevsp, errbuf) != OK && LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.warning("Error: {}" + errbuf.toString());
        }
        if (source == null || source.isEmpty()) {
            for (PcapIf dev : alldevsp) {
                for (PcapAddr addr : dev.getAddresses()) {
                    if (addr.getAddr().getSaFamily() == SockAddr.Family.AF_INET && addr.getAddr().getData() != null) {
                        Inet4Address d = Inet4Address.valueOf(addr.getAddr().getData());
                        if (!d.equals(Inet4Address.LOCALHOST) && !d.equals(Inet4Address.ZERO)) {
                            return dev;
                        }
                    }
                }
            }
        } else {
            for (PcapIf dev : alldevsp) {
                if (dev.getName().equals(source)) {
                    return dev;
                }
            }
        }
        throw new DeviceNotFoundException("No device connected to the network.");
    }
322138
def create_interface(self):
        """"""
        return Interface(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
1311429
def main(args=sys.argv[1:]):
    
    if not is_pywin32_available():
        sys.stderr.write('win32com module not found')
        return -1

    try:
        options, argv = parse_options(args)
        export_img(argv[0], argv[1], options.pagenum, options.pagename)
        return 0
    except (IOError, OSError, IndexError) as err:
        sys.stderr.write("error: %s" % err)
        return -1
1298701
def rdpcap(filename, count=-1):
    """"""
    with PcapReader(filename) as pcap:
        return pcap.read_all(count=count)
727893
def open_ports(start, end, protocol="TCP"):
    """"""
    _args = ['open-port']
    _args.append('{}-{}/{}'.format(start, end, protocol))
    subprocess.check_call(_args)
1069646
def OpenFile(self, windows_path):
    
    path_spec = self._path_resolver.ResolvePath(windows_path)
    if path_spec is None:
      return None

    return self._file_system.GetFileObjectByPathSpec(path_spec)
821123
def open(self, visible=False):
    
    if self.client:
      raise MatlabConnectionError('Matlab(TM) COM client is still active. Use close to '
                      'close it')
    self.client = win32com.client.Dispatch('matlab.application')
    self.client.visible = visible