Validates whether a network address is reachable.

@param hostname host name of the network address
@param port port of the network address
@return whether the network address is reachable
556994
public static boolean isAddressReachable(String hostname, int port) {
    try (Socket socket = new Socket(hostname, port)) {
      return true;
    } catch (IOException e) {
      return false;
    }
  }
581571
public static boolean isTcpPortAvailable(int currentPort) {
        try {
            Socket socket = SocketFactory.getDefault().createSocket(InetAddress.getLocalHost(), currentPort);
            socket.close();
            return false;
        } catch (Throwable e) {
            return true;
        }
    }
215190
public static int getAvailablePort(String host, int port, int maxPort) {
        if (isAnyHost(host)
            || isLocalHost(host)
            || isHostInNetworkCard(host)) {
            if (port < MIN_PORT) {
                port = MIN_PORT;
            }
            for (int i = port; i <= maxPort; i++) {
                ServerSocket ss = null;
                try {
                    ss = new ServerSocket();
                    ss.bind(new InetSocketAddress(host, i));
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("ip:{} port:{} is available", host, i);
                    }
                    return i;
                } catch (IOException e) {
                    // continue
                    if (LOGGER.isWarnEnabled()) {
                        LOGGER.warn("Can't bind to address [{}:{}], " +
                            "Maybe 1) The port has been bound. " +
                            "2) The network card of this host is not exists or disable. " +
                            "3) The host is wrong.", host, i);
                    }
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Begin try next port(auto +1):{}", i + 1);
                    }
                } finally {
                    IOUtils.closeQuietly(ss);
                }
            }
            throw new SofaRpcRuntimeException("Can't bind to ANY port of " + host + ", please check config");
        } else {
            throw new SofaRpcRuntimeException("The host " + host
                + " is not found in network cards, please check config");
        }
    }
526116
@Override
    protected void onValidation(final String contactNode, final String defaultPort)
    {
        if (contactNode != null)
        {
            // allow configuration as comma-separated list of host:port
            // addresses without the default port
            boolean allAddressesHaveHostAndPort = true;

            for (String node : contactNode.split(Constants.COMMA))
            {
                if (StringUtils.countMatches(node, Constants.COLON) == 1)
                {
                    // node is given with hostname and port
                    // count == 1 is to exclude IPv6 addresses
                    if (StringUtils.isNumeric(node.split(Constants.COLON)[1]))
                    {
                        continue;
                    }
                }

                allAddressesHaveHostAndPort = false;
                break;
            }

            if (allAddressesHaveHostAndPort)
            {
                return;
            }
        }

        // fall back to the generic validation which requires the default port
        // to be set
        super.onValidation(contactNode, defaultPort);
    }
763730
private synchronized static boolean isWorkingHost(String host) {
        if (workerHost == null) {
            workerHost = host;
            return true;
        } else {
            return host.equals(workerHost);
        }
    }
1336741
public boolean isHostProxyable(String host) {
        return getProxyHost() != null
                && getProxyPort() > 0
                && (nonProxyPattern == null || !nonProxyPattern.matcher(host)
                        .matches());
    }
263506
def is_port_open(port, host="127.0.0.1"):
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((host, int(port)))
        s.shutdown(2)
        return True
    except Exception as e:
        return False
915999
protected boolean isConnected(final String host, final int port, final int timeoutInMs,
      final ErrorHandler errorHandler) {
    final Socket socket = new Socket();
    return isConnected(socket, host, port, timeoutInMs, errorHandler);
  }
965709
public static InetSocketAddress createWithResolveRetry(
    String hostname,
    int port
  ) {
    return createWithResolveRetry(
      hostname,
      port,
      DEFAULT_DELAY_MILLIS,
      DEFAULT_MAX_ATTEMPTS
    );
  }
321019
public static boolean available(final String host, final int port)
	{
		Socket socket = null;
		try
		{
			socket = newSocket(host, port);
			return false;
		}
		catch (final IOException ignored)
		{
			return true;
		}
		finally
		{
			if (!closeClientSocket(socket))
			{
				LOGGER.error("Socket could not be closed on host " + host + " on port " + port);
			}
		}
	}
905572
public boolean verifyHostname(String hostname, String pattern) {
        // Basic sanity checks
        // Check length == 0 instead of .isEmpty() to support Java 5.
        if ((hostname == null) || (hostname.length() == 0) || (hostname.startsWith("."))
            || (hostname.endsWith(".."))) {
            // Invalid domain name
            return false;
        }
        if ((pattern == null) || (pattern.length() == 0) || (pattern.startsWith("."))
            || (pattern.endsWith(".."))) {
            // Invalid pattern/domain name
            return false;
        }

        // Normalize hostname and pattern by turning them into absolute domain names if they are not
        // yet absolute. This is needed because server certificates do not normally contain absolute
        // names or patterns, but they should be treated as absolute. At the same time, any hostname
        // presented to this method should also be treated as absolute for the purposes of matching
        // to the server certificate.
        //   www.android.com  matches www.android.com
        //   www.android.com  matches www.android.com.
        //   www.android.com. matches www.android.com.
        //   www.android.com. matches www.android.com
        if (!hostname.endsWith(".")) {
            hostname += '.';
        }
        if (!pattern.endsWith(".")) {
            pattern += '.';
        }
        // hostname and pattern are now absolute domain names.

        pattern = pattern.toLowerCase(Locale.US);
        // hostname and pattern are now in lower case -- domain names are case-insensitive.

        if (!pattern.contains("*")) {
            // Not a wildcard pattern -- hostname and pattern must match exactly.
            return hostname.equals(pattern);
        }
        // Wildcard pattern

        // WILDCARD PATTERN RULES:
        // 1. Asterisk (*) is only permitted in the left-most domain name label and must be the
        //    only character in that label (i.e., must match the whole left-most label).
        //    For example, *.example.com is permitted, while *a.example.com, a*.example.com,
        //    a*b.example.com, a.*.example.com are not permitted.
        // 2. Asterisk (*) cannot match across domain name labels.
        //    For example, *.example.com matches test.example.com but does not match
        //    sub.test.example.com.
        // 3. Wildcard patterns for single-label domain names are not permitted.

        if ((!pattern.startsWith("*.")) || (pattern.indexOf('*', 1) != -1)) {
            // Asterisk (*) is only permitted in the left-most domain name label and must be the only
            // character in that label
            return false;
        }

        // Optimization: check whether hostname is too short to match the pattern. hostName must be at
        // least as long as the pattern because asterisk must match the whole left-most label and
        // hostname starts with a non-empty label. Thus, asterisk has to match one or more characters.
        if (hostname.length() < pattern.length()) {
            // hostname too short to match the pattern.
            return false;
        }

        if ("*.".equals(pattern)) {
            // Wildcard pattern for single-label domain name -- not permitted.
            return false;
        }

        // hostname must end with the region of pattern following the asterisk.
        String suffix = pattern.substring(1);
        if (!hostname.endsWith(suffix)) {
            // hostname does not end with the suffix
            return false;
        }

        // Check that asterisk did not match across domain name labels.
        int suffixStartIndexInHostname = hostname.length() - suffix.length();
        return (suffixStartIndexInHostname <= 0)
            || (hostname.lastIndexOf('.', suffixStartIndexInHostname - 1) == -1);
    }
968095
public static NetworkPort remoteDatagramPort(String hostname, int port){
        return new RemoteNetworkPort(hostname, port, NetworkPort.Type.UDP);
    }
251259
private boolean portAvailable(final int port) {
    ServerSocket socket = null;
    try {
      socket = new ServerSocket(port);
      return true;
    } catch (IOException ignored) {
      return false;
    } finally {
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException e) {
          log.error("Couldn't close socket on port {} when checking availability: {}", port, e);
        }
      }
    }
  }
273223
private boolean isValidEndpoint(String endpoint) {
    if (InetAddressValidator.getInstance().isValid(endpoint)) {
      return true;
    }

    // endpoint may be a hostname
    // refer https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
    // why checks are done like below
    if (endpoint.length() < 1 || endpoint.length() > 253) {
      return false;
    }

    for (String label : endpoint.split("\\.")) {
      if (label.length() < 1 || label.length() > 63) {
        return false;
      }

      if (!(label.matches("^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$"))) {
        return false;
      }
    }

    return true;
  }
963009
public static boolean isHostInNetworkCard(String host) {
        try {
            InetAddress addr = InetAddress.getByName(host);
            return NetworkInterface.getByInetAddress(addr) != null;
        } catch (Exception e) {
            return false;
        }
    }
1332194
public boolean isValidAddress(NetworkParameters network) {
      byte version = getVersion();
      if (getAllAddressBytes().length != 21) {
         return false;
      }
      return ((byte) (network.getStandardAddressHeader() & 0xFF)) == version
            || ((byte) (network.getMultisigAddressHeader() & 0xFF)) == version;
   }
736695
public void setPort(int port)
    {
        if (_address == null || _address.getHostName() == null)
            _address= new InetSocketAddress(port);
        else
            _address= new InetSocketAddress(_address.getHostName(), port);
    }