public static HostAndPort fromString ( String hostPort , int defaultPort ) { if ( hostPort == null ) throw new NullPointerException ( "hostPort == null" ) ; String host = hostPort ; int endHostIndex = hostPort . length ( ) ; if ( hostPort . startsWith ( "[" ) ) { // Bracketed IPv6 endHostIndex = hostPort . lastIndexOf ( ' ' ) + 1 ; host = hostPort . substring ( 1 , endHostIndex == 0 ? 1 : endHostIndex - 1 ) ; if ( ! Endpoint . newBuilder ( ) . parseIp ( host ) ) { // reuse our IPv6 validator throw new IllegalArgumentException ( hostPort + " contains an invalid IPv6 literal" ) ; } } else { int colonIndex = hostPort . indexOf ( ' ' ) , nextColonIndex = hostPort . lastIndexOf ( ' ' ) ; if ( colonIndex >= 0 ) { if ( colonIndex == nextColonIndex ) { // only 1 colon host = hostPort . substring ( 0 , colonIndex ) ; endHostIndex = colonIndex ; } else if ( ! Endpoint . newBuilder ( ) . parseIp ( hostPort ) ) { // reuse our IPv6 validator throw new IllegalArgumentException ( hostPort + " is an invalid IPv6 literal" ) ; } } } if ( host . isEmpty ( ) ) throw new IllegalArgumentException ( hostPort + " has an empty host" ) ; if ( endHostIndex + 1 < hostPort . length ( ) && hostPort . charAt ( endHostIndex ) == ' ' ) { return new HostAndPort ( host , validatePort ( hostPort . substring ( endHostIndex + 1 ) , hostPort ) ) ; } return new HostAndPort ( host , defaultPort ) ; }
Constructs a host - port pair from the given string defaulting to the indicated port if absent