Check whether we can connect to a local Unix socket
551458
public static boolean canConnectUnixSocket(File path) {
        try (UnixSocketChannel channel = UnixSocketChannel.open()) {
            return channel.connect(new UnixSocketAddress(path));
        } catch (IOException e) {
            return false;
        }
    }
1257553
def _check_tunnel(self, _srv):
        
        if self.skip_tunnel_checkup:
            self.tunnel_is_up[_srv.local_address] = True
            return
        self.logger.info('Checking tunnel to: {0}'.format(_srv.remote_address))
        if isinstance(_srv.local_address, string_types):  # UNIX stream
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(TUNNEL_TIMEOUT)
        try:
            # Windows raises WinError 10049 if trying to connect to 0.0.0.0
            connect_to = ('127.0.0.1', _srv.local_port) \
                if _srv.local_host == '0.0.0.0' else _srv.local_address
            s.connect(connect_to)
            self.tunnel_is_up[_srv.local_address] = _srv.tunnel_ok.get(
                timeout=TUNNEL_TIMEOUT * 1.1
            )
            self.logger.debug(
                'Tunnel to {0} is DOWN'.format(_srv.remote_address)
            )
        except socket.error:
            self.logger.debug(
                'Tunnel to {0} is DOWN'.format(_srv.remote_address)
            )
            self.tunnel_is_up[_srv.local_address] = False

        except queue.Empty:
            self.logger.debug(
                'Tunnel to {0} is UP'.format(_srv.remote_address)
            )
            self.tunnel_is_up[_srv.local_address] = True
        finally:
            s.close()
284860
def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool:
        
        try:
            # see if we can resolve the host name -- tells us if there is
            # a DNS listening
            host = socket.gethostbyname(remote_server)
            # connect to the host -- tells us if it's reachable
            sock = socket.create_connection((host, 80), 2)
            sock.close()
            return True
        except Exception as e:
            logging.error(e)
            return False
1060401
function listen() {
  var args = []
    , port = this.conf.get(ConfigKey.PORT)
    , socket = this.conf.get(ConfigKey.UNIXSOCKET)
    , perm = this.conf.get(ConfigKey.UNIXSOCKETPERM)
    , backlog = this.conf.get(ConfigKey.TCP_BACKLOG)
    , cb = typeof arguments[arguments.length - 1] === 'function'
      ? arguments[arguments.length - 1] : null
    , tcp
    , unix;

  if(socket) {
    unix = this._unix = new UnixServer(this);
  }

  // tcp: server.listen(port, [host], [backlog], [callback])
  // unix socket: server.listen(path, [callback])

  // port zero means don't listen on a tcp port
  if(port !== 0) {
    tcp = this._tcp = new TcpServer(this);

    // port comes first
    args.unshift(port);

    // backlog is penultimate argument
    if(typeof backlog === 'number') {
      args.push(backlog);
    }

    //console.dir(args);

    // cb is last argument
    if(cb) args.push(cb);

    function onListen() {
      // for server info, the actual port or socket in use
      // stored on the state, null if listen was never called
      // or if the bind failed, could also be a unix socket
      var addr = tcp.address();
      var port = addr.port;
      this.state.addr = addr;

      // only write pid if we listen
      if(this._daemonized) {
        daemon.pid.write(this.conf);
      }

      this.emit('listen', port);
      this.log.notice('accepting connections on port %s', port);

      // might be listening on a unix socket too
      if(unix) unix.listen(socket, perm);
    }

    tcp.once('listening', onListen.bind(this));
    tcp.listen.apply(tcp, args);
  // just a unix socket
  }else if(unix) {
    unix.listen(socket, perm);
  }
}
612751
def is_enabled(iface):
    '''
    
    '''
    cmd = ['netsh', 'interface', 'show', 'interface', 'name={0}'.format(iface)]
    iface_found = False
    for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
        if 'Connect state:' in line:
            iface_found = True
            return line.split()[-1] == 'Connected'
    if not iface_found:
        raise CommandExecutionError(
            'Interface \'{0}\' not found'.format(iface)
        )
    return False
14423
def server_check(arg):
    
    if arg.startswith(('http://', 'https://', 'http+unix://')):
        return arg
    if arg.startswith('./'):
        arg = os.path.abspath(arg)
    elif not arg.startswith('/'):
        raise argparse.ArgumentTypeError(
            'Unix socket path must start with / or ./')
    # assume it is a unix socket
    return 'http+unix://{}'.format(url_escape(arg, ''))
1110814
def _connect(self):

        '''
            
        '''

        if self.connection_type.lower() == 'tcp':
            self.connection = sockets.setup_tcp_socket(self.location, self.port)

        elif self.connection_type.lower() == 'unix':
            self.connection = sockets.setup_domain_socket(self.location)

        return
469571
def return_socket(self, sock_info):
        """"""
        if self.pid != os.getpid():
            self.reset()
        else:
            if sock_info.pool_id != self.pool_id:
                sock_info.close()
            elif not sock_info.closed:
                sock_info.update_last_checkin_time()
                with self.lock:
                    self.sockets.appendleft(sock_info)

        self._socket_semaphore.release()
        with self.lock:
            self.active_sockets -= 1
648009
def _check_with_socket(self, sock_info):
        
        start = _time()
        try:
            return (sock_info.ismaster(self._pool.opts.metadata,
                                       self._topology.max_cluster_time()),
                    _time() - start)
        except OperationFailure as exc:
            # Update max cluster time even when isMaster fails.
            self._topology.receive_cluster_time(
                exc.details.get('$clusterTime'))
            raise
324087
def _connect(self):
        ""
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.settimeout(self.socket_timeout)
        sock.connect(self.path)
        return sock
1238826
def check_port(port, host, timeout=10):
    
    logger.info("trying to open connection to %s:%s", host, port)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        logger.info("was connection successful? errno: %s", result)
        if result == 0:
            logger.debug('port is opened: %s:%s' % (host, port))
            return True
        else:
            logger.debug('port is closed: %s:%s' % (host, port))
            return False
    finally:
        sock.close()
154313
def run(self):
        
        # Bind the socket to the port
        logging.info("Server starts socket on {addr}".format(addr=self.server_address))

        # Create a UDS socket
        if six.PY2:
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.listen(sock)
            sock.close()
        else:
            with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
                self.listen(sock)
        try:
            os.unlink(self.server_address)
        except OSError:
            if os.path.exists(self.server_address):
                raise
        return
150669
def ping():
    '''
    
    '''
    try:
        client = _get_client()
        client.info()
    except SaltSystemExit as err:
        log.warning(err)
        return False

    return True
1338659
def parent_is_inet():
    
    result = False
    sock = socket.fromfd(
        sys.__stdin__.fileno(),
        socket.AF_INET,
        socket.SOCK_RAW)
    try:
        sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
        result = True
    except (OSError, socket.error) as err:
        if not err.args[0] == errno.ENOTSOCK:
            result = True
    return result
34553
def local_ip():
    """"""
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith('127.'):
        # Check eth0, eth1, eth2, en0, ...
        interfaces = [
            i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
        ]  # :(
        for interface in interfaces:
            try:
                ip = interface_ip(interface)
                break
            except IOError:
                pass
    return ip
239797
def _socket_connect(self):
        """"""
        self.usage_count = 0
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            s.connect((self._host, self._port))
            self.__stream = self.__backend.register_stream(s, **self.__kwargs)
            self.__stream.set_close_callback(self._socket_close)
            self.__alive = True
        except socket.error, error:
            raise InterfaceError(error)
1227873
def _check_file_exists_unix(self, remote_cmd=""):
        """"""
        if self.direction == "put":
            self.ssh_ctl_chan._enter_shell()
            remote_cmd = "ls {}".format(self.file_system)
            remote_out = self.ssh_ctl_chan.send_command(
                remote_cmd, expect_string=r"[\$#]"
            )
            self.ssh_ctl_chan._return_cli()
            return self.dest_file in remote_out
        elif self.direction == "get":
            return os.path.exists(self.dest_file)