public static HostAndPort fromString ( String hostPortString ) { checkNotNull ( hostPortString ) ; String host ; String portString = null ; boolean hasBracketlessColons = false ; if ( hostPortString . startsWith ( "[" ) ) { String [ ] hostAndPort = getHostAndPortFromBracketedHost ( hostPortString ) ; host = hostAndPort [ 0 ] ; portString = hostAndPort [ 1 ] ; } else { int colonPos = hostPortString . indexOf ( ' ' ) ; if ( colonPos >= 0 && hostPortString . indexOf ( ' ' , colonPos + 1 ) == - 1 ) { // Exactly 1 colon. Split into host:port. host = hostPortString . substring ( 0 , colonPos ) ; portString = hostPortString . substring ( colonPos + 1 ) ; } else { // 0 or 2+ colons. Bare hostname or IPv6 literal. host = hostPortString ; hasBracketlessColons = ( colonPos >= 0 ) ; } } int port = NO_PORT ; if ( ! Strings . isNullOrEmpty ( portString ) ) { // Try to parse the whole port string as a number. // JDK7 accepts leading plus signs. We don't want to. checkArgument ( ! portString . startsWith ( "+" ) , "Unparseable port number: %s" , hostPortString ) ; try { port = Integer . parseInt ( portString ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Unparseable port number: " + hostPortString ) ; } checkArgument ( isValidPort ( port ) , "Port number out of range: %s" , hostPortString ) ; } return new HostAndPort ( host , port , hasBracketlessColons ) ; }
Split a freeform string into a host and port without strict validation .