Check a port by connecting to it. Try only 200ms.
518957
private static boolean isPortOpen(InetAddress pAddress, int pPort) {
        Socket socket = null;
        try {
            socket = new Socket();
            socket.setReuseAddress(true);
            SocketAddress sa = new InetSocketAddress(pAddress, pPort);
            socket.connect(sa, 200);
            return socket.isConnected();
        } catch (IOException e) {
            return false;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // Best effort. Hate that close throws an IOException, btw. Never saw a real use case for that.
                }
            }
        }
    }
516739
def check_network_connection(server, port):
    '''
    
    '''
    logger = logging.getLogger(__name__)
    logger.debug("Checking network connection to server '%s'...", server)
    try:
        # see if we can resolve the host name -- tells us if there is
        # a DNS listening
        host = socket.gethostbyname(server)
        # connect to the host -- tells us if the host is actually
        # reachable
        sock = socket.create_connection((host, port), 2)
        sock.close()
    except Exception:  # pragma: no cover
        logger.debug("Network connection not working")
        return False
    logger.debug("Network connection working")
    return True
764607
def is_server_running(host, port):
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        return s.connect_ex((host, port)) == 0
    finally:
        s.close()
836316
def _mksocket(host, port, q, done, stop):
    """"""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
    attempt = 0
    while not stop.is_set():
        try:
            s.connect((host, port))
            return s
        except Exception as ex:
            # Simple exponential backoff: sleep for 1,2,4,8,16,30,30...
            time.sleep(min(30, 2 ** attempt))
            attempt += 1
1017363
def connect(self):
    """"""
    if self.sock is not None:
      return
    backoff = 0.01
    while True:
      try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        sock.connect((self.host, self.port))
        self.sock = sock
        return
      except socket.error:
        time.sleep(random.uniform(0, 2.0*backoff))
        backoff = min(backoff*2.0, 5.0)
790115
def timed_connectivity_check(self, event):
        """"""
        self.status = self._can_connect()
        self.log('Timed connectivity check:', self.status, lvl=verbose)

        if self.status:
            if not self.old_status:
                self.log('Connectivity gained')
                self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, on=True, force=True))
        else:
            if self.old_status:
                self.log('Connectivity lost', lvl=warn)
                self.old_status = False
                self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, off=True, force=True))

        self.old_status = self.status
158567
def a_connection_timeout(ctx):
    """"""
    prompt = ctx.ctrl.after
    ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
    ctx.device.connected = False
    ctx.finished = True
    raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname)
592937
def is_running(self, port):
        """"""
        try:
            con = self.client('localhost:%s' % port)
            con.admin.command('ping')
            return True
        except (AutoReconnect, ConnectionFailure, OperationFailure):
            # Catch OperationFailure to work around SERVER-31916.
            return False
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
163489
def tick(self):
        """"""
        try:
            s, addr = self.socket.accept()
            if self.stats['Enabled']:
                self.stats['Accepts'] += 1
            if not self.ready:
                return

            prevent_socket_inheritance(s)
            if hasattr(s, 'settimeout'):
                s.settimeout(self.timeout)

            mf = MakeFile
            ssl_env = {}
            # if ssl cert and key are set, we try to be a secure HTTP server
            if self.ssl_adapter is not None:
                try:
                    s, ssl_env = self.ssl_adapter.wrap(s)
                except errors.NoSSLError:
                    msg = (
                        'The client sent a plain HTTP request, but '
                        'this server only speaks HTTPS on this port.'
                    )
                    buf = [
                        '%s 400 Bad Request\r\n' % self.protocol,
                        'Content-Length: %s\r\n' % len(msg),
                        'Content-Type: text/plain\r\n\r\n',
                        msg,
                    ]

                    sock_to_make = s if six.PY3 else s._sock
                    wfile = mf(sock_to_make, 'wb', io.DEFAULT_BUFFER_SIZE)
                    try:
                        wfile.write(''.join(buf).encode('ISO-8859-1'))
                    except socket.error as ex:
                        if ex.args[0] not in errors.socket_errors_to_ignore:
                            raise
                    return
                if not s:
                    return
                mf = self.ssl_adapter.makefile
                # Re-apply our timeout since we may have a new socket object
                if hasattr(s, 'settimeout'):
                    s.settimeout(self.timeout)

            conn = self.ConnectionClass(self, s, mf)

            if not isinstance(self.bind_addr, six.string_types):
                # optional values
                # Until we do DNS lookups, omit REMOTE_HOST
                if addr is None:  # sometimes this can happen
                    # figure out if AF_INET or AF_INET6.
                    if len(s.getsockname()) == 2:
                        # AF_INET
                        addr = ('0.0.0.0', 0)
                    else:
                        # AF_INET6
                        addr = ('::', 0)
                conn.remote_addr = addr[0]
                conn.remote_port = addr[1]

            conn.ssl_env = ssl_env

            try:
                self.requests.put(conn)
            except queue.Full:
                # Just drop the conn. TODO: write 503 back?
                conn.close()
                return
        except socket.timeout:
            # The only reason for the timeout in start() is so we can
            # notice keyboard interrupts on Win32, which don't interrupt
            # accept() by default
            return
        except socket.error as ex:
            if self.stats['Enabled']:
                self.stats['Socket Errors'] += 1
            if ex.args[0] in errors.socket_error_eintr:
                # I *think* this is right. EINTR should occur when a signal
                # is received during the accept() call; all docs say retry
                # the call, and I *think* I'm reading it right that Python
                # will then go ahead and poll for and handle the signal
                # elsewhere. See
                # https://github.com/cherrypy/cherrypy/issues/707.
                return
            if ex.args[0] in errors.socket_errors_nonblocking:
                # Just try again. See
                # https://github.com/cherrypy/cherrypy/issues/479.
                return
            if ex.args[0] in errors.socket_errors_to_ignore:
                # Our socket was closed.
                # See https://github.com/cherrypy/cherrypy/issues/686.
                return
            raise
194716
def await_connection(host, port):
    """"""
    for i in range(CONNECT_ATTEMPTS):
        try:
            conn = socket.create_connection((host, port), CONNECT_TIMEOUT)
            conn.close()
            return True
        except (IOError, socket.error):
            time.sleep(1)
    return False
1260148
def checkTimeout(self, now):
        """"""
        log.debug("checking for timeout on session %s", self)
        if now - self.last_update > self.timeout:
            raise TftpTimeout("Timeout waiting for traffic")
896422
def find_free_port():
    """"""
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        sock.bind(('', 0))
        return sock.getsockname()[1]
1038113
def _can_connect(self):
        """"""
        self.log('Trying to reach configured connectivity check endpoint', lvl=verbose)

        try:
            socket.setdefaulttimeout(self.config.timeout)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((self.config.host, self.config.port))
            return True
        except Exception as ex:
            self.log(ex, pretty=True, lvl=debug)
            return False
328319
@Nonnull
  public static ENetworkPortStatus checkPortOpen (@Nonnull @Nonempty final String sHostName,
                                                  @Nonnegative final int nPort,
                                                  @Nonnegative final int nTimeoutMillisecs)
  {
    ValueEnforcer.notEmpty (sHostName, "Hostname");
    ValueEnforcer.isGE0 (nPort, "Port");
    ValueEnforcer.isGE0 (nTimeoutMillisecs, "TimeoutMillisecs");

    LOGGER.info ("Checking TCP port status for " +
                 sHostName +
                 ":" +
                 nPort +
                 " with timeouf of " +
                 nTimeoutMillisecs +
                 " ms");

    try (final Socket aSocket = new Socket ())
    {
      aSocket.setReuseAddress (true);
      final SocketAddress aSocketAddr = new InetSocketAddress (sHostName, nPort);
      aSocket.connect (aSocketAddr, nTimeoutMillisecs);
      return ENetworkPortStatus.PORT_IS_OPEN;
    }
    catch (final IOException ex)
    {
      // Can also be:
      // Connection refused: connect
      if (ex.getMessage ().startsWith ("Connection refused"))
        return ENetworkPortStatus.PORT_IS_CLOSED;
      if (ex instanceof java.net.UnknownHostException)
        return ENetworkPortStatus.HOST_NOT_EXISTING;
      if (ex instanceof java.net.SocketTimeoutException)
        return ENetworkPortStatus.CONNECTION_TIMEOUT;
      if (ex instanceof java.net.ConnectException)
      {
        // E.g. for port 0
        return ENetworkPortStatus.GENERIC_IO_ERROR;
      }
      LOGGER.error ("Other error checking TCP port status", ex);
      return ENetworkPortStatus.GENERIC_IO_ERROR;
    }
  }
1230034
private static boolean waitForServerDown(int port, long timeout) {
    long start = System.currentTimeMillis();
    while (true) {
      try {
        Socket sock = new Socket("localhost", port);
        try {
          OutputStream outstream = sock.getOutputStream();
          outstream.write("stat".getBytes());
          outstream.flush();
        } finally {
          sock.close();
        }
      } catch (IOException e) {
        return true;
      }

      if (System.currentTimeMillis() > start + timeout) {
        break;
      }
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        // ignore
      }
    }
    return false;
  }
906751
def run(self):
        """"""
        while not self.stopped.isSet():
            try:
                # if the current state is idle, just block and wait forever
                # if the current state is any other state, then a timeout of 200ms should
                # be reasonable in all cases.
                timeout = (self._state != 'idle') and 0.2 or None
                rdlist, _, _ = select.select([self._socket.fileno()], [], [], timeout)
                if not rdlist:
                    if self._state != 'idle':
                        self._state = 'idle'
                    continue
                data = self._socket.recv(1024)
                if not data:
                    # check if the socket is still valid
                    try:
                        os.fstat(recv._socket.fileno())
                    except socket.error:
                        break
                    continue
                code = utils.mangleIR(data, ignore_errors=True)
                codeName = self.codeMap.get(code)
                # some manufacturers repeat their IR codes several times in rapid
                # succession. by tracking the last code, we can eliminate redundant
                # state changes
                if codeName and (self._state != codeName):
                    self._state = codeName
                    for callback in self._callbacks:
                        callback(codeName)
            except:
                time.sleep(0.1)