在单个字符串中创建给定主机和可选端口的InetSocketAddress,这允许根据rfc2732以字符串形式提供IP4或IP6地址(包括端口)
/* * Copyright 2014, The Sporting Exchange Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//*时 代 Java 公 众 号 - nowjava.com 提供*/ //package com.nowjava; import java.net.InetSocketAddress; public class Main { public static void main(String[] argv) throws Exception { String address = "nowjava.com"; System.out.println(createInetSocketAddress(address)); } /** * <p>Creates an InetSocketAddress given a host and optional port in a single String</p> * <p/> * <p>This allows either IP4 or IP6 addresses (including port) to be provided as Strings as per rfc2732</p> * * @param address the address in one of the following formats (the braces '[]'and colon ':' are literal here): * host<br> * [host]<br> * [host]:port<br> * [host]port<br> * ip4host:port<br> * <p>Assumes port 0 if non is specified.</p> * <p/> * <p> As per java.net.InetSocketAddress * A port number of zero will let the system pick up an ephemeral port in a bind operation.</p> */ public static InetSocketAddress createInetSocketAddress(String address) { return createInetSocketAddress(address, 0); } /** * <p>Creates an InetSocketAddress given a host and optional port in a single String * <p/> * <p>This allows either IP4 or IP6 addresses (including port) to be provided as Strings as per rfc2732</p> * * @param address the address in one of the following formats (the braces '[]'and colon ':' are literal here): * host<br> * [host]<br> * [host]:port<br> * [host]port<br> * ip4host:port<br> * @param defaultPort The default port to be used ONLY IF the string does not specify a port * @see java.net.InetSocketAddress */ public static InetSocketAddress createInetSocketAddress(String address, int defaultPort) { String original = address.trim(); String host = original;/*n o w j a v a . c o m*/ int port = defaultPort; if (host.startsWith("[")) { // it is an address in [host] or [host]port format String[] s = original.split("\\]"); if (s.length > 1) { if (s[1].startsWith(":")) { s[1] = s[1].substring(1); } port = computePort(s[1], 0); } host = s[0].substring(1); } if (host.indexOf(":") == host.lastIndexOf(":") && (host.indexOf(":") > -1)) {