Java examples for Network:Network Address
Parse space delimited address [:port] string and return array of InetSocketAddress.
/*//from w w w . j a va 2 s.com * Copyright (c) 2004 by Cosylab * * The full license specifying the redistribution, modification, usage and other * rights and obligations is included with the distribution of this project in * the file "LICENSE-CAJ". If the license is not included visit Cosylab web site, * <http://www.cosylab.com>. * * THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, NOT EVEN THE * IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE, ASSUMES * _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, * OR REDISTRIBUTION OF THIS SOFTWARE. */ //package com.java2s; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public static void main(String[] argv) throws Exception { String list = "java2s.com"; int defaultPort = 2; System.out.println(java.util.Arrays.toString(getSocketAddressList( list, defaultPort))); } /** * Parse space delimited address[:port] string and return array of <code>InetSocketAddress</code>. * @param list space delimited address[:port] string. * @param defaultPort port take if not specified. * @return array of <code>InetSocketAddress</code>. */ public static InetSocketAddress[] getSocketAddressList(String list, int defaultPort) { return getSocketAddressList(list, defaultPort, null); } /** * Parse space delimited address[:port] string and return array of <code>InetSocketAddress</code>. * @param list space delimited address[:port] string. * @param defaultPort port take if not specified. * @param appendList list to be appended. * @return array of <code>InetSocketAddress</code>. */ public static InetSocketAddress[] getSocketAddressList(String list, int defaultPort, InetSocketAddress[] appendList) { ArrayList al = new ArrayList(); // parse string StringTokenizer st = new StringTokenizer(list); while (st.hasMoreTokens()) { int port = defaultPort; String address = st.nextToken(); // check port int pos = address.indexOf(':'); if (pos >= 0) { try { port = Integer.parseInt(address.substring(pos + 1)); } catch (NumberFormatException nfe) { /* noop */ } address = address.substring(0, pos); } // add parsed address al.add(new InetSocketAddress(address, port)); } // copy to array int appendSize = (appendList == null) ? 0 : appendList.length; InetSocketAddress[] isar = new InetSocketAddress[al.size() + appendSize]; al.toArray(isar); if (appendSize > 0) System.arraycopy(appendList, 0, isar, al.size(), appendSize); return isar; } }