Java HTTP Port Find parse(final String desc, final int defaultPort)

Here you can find the source of parse(final String desc, final int defaultPort)

Description

Parse an address string such as host:port or *:port .

License

Apache License

Declaration

public static InetSocketAddress parse(final String desc, final int defaultPort) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.net.InetSocketAddress;

public class Main {
    /** Parse an address string such as {@code host:port} or {@code *:port}. */
    public static InetSocketAddress parse(final String desc, final int defaultPort) {
        String hostStr;//from w  ww  . ja  va2s.  c om
        String portStr;

        if (desc.startsWith("[")) {
            // IPv6, as a raw IP address.
            //
            final int hostEnd = desc.indexOf(']');
            if (hostEnd < 0) {
                throw new IllegalArgumentException("invalid IPv6: " + desc);
            }

            hostStr = desc.substring(1, hostEnd);
            portStr = desc.substring(hostEnd + 1);
        } else {
            // IPv4, or a host name.
            //
            final int hostEnd = desc.indexOf(':');
            hostStr = 0 <= hostEnd ? desc.substring(0, hostEnd) : desc;
            portStr = 0 <= hostEnd ? desc.substring(hostEnd) : "";
        }

        if ("".equals(hostStr)) {
            hostStr = "*";
        }
        if (portStr.startsWith(":")) {
            portStr = portStr.substring(1);
        }

        final int port;
        if (portStr.length() > 0) {
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("invalid port: " + desc);
            }
        } else {
            port = defaultPort;
        }

        if ("*".equals(hostStr)) {
            return new InetSocketAddress(port);
        }
        return InetSocketAddress.createUnresolved(hostStr, port);
    }
}

Related

  1. issueHttpRequest(String methodName, int[] rc, String host, String port, String path)
  2. isTcpPortOpen(int port)
  3. isTcpPortOpenCallable(final int port)
  4. isTcpPortOpenCallable(final int port)
  5. loadStringSupportedType(String javaType)
  6. parse(String specs, int defaultPort)
  7. parseCommaDelimitedHosts2(String hosts, int port_range)
  8. parseHostPort(String s)
  9. parsePort(String s)