/******************************************************************************* * Copyright (c) 2007, 2011 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.db.management.discovery; import java.net.InetSocketAddress; /** * @author Tuukka Lehtonen */ public final class InetAddressUtils { /** * @param hostAndPort * @return * @throws IllegalArgumentException */ public static InetSocketAddress parse(String hostAndPort) throws IllegalArgumentException { String[] split = hostAndPort.split(":"); if (split.length != 2) throw new IllegalArgumentException("address does not contain a port, missing ':' character"); return new InetSocketAddress(split[0], Integer.parseInt(split[1])); } /** * @param hostAndPort * @return * @throws IllegalArgumentException */ public static InetSocketAddress parseUnresolved(String hostAndPort) throws IllegalArgumentException { String[] split = hostAndPort.split(":"); if (split.length != 2) throw new IllegalArgumentException("address does not contain a port, missing ':' character"); return InetSocketAddress.createUnresolved(split[0], Integer.parseInt(split[1])); } public static String toHostString(InetSocketAddress address) { if (address == null) return "null"; return address.getHostName() + ":" + address.getPort(); } /** * @param hostAndPort * @return * @throws IllegalArgumentException */ public static InetSocketAddress parseHostAddressPort(String hostAddressPort) throws IllegalArgumentException { String[] split = hostAddressPort.split(":"); if (split.length != 2) throw new IllegalArgumentException("address not in format '[/]
:port', does not contain a port, missing ':' character: " + hostAddressPort); String[] split2 = split[0].split("/"); if (split2.length == 1) return new InetSocketAddress(split[0], Integer.parseInt(split[1])); if (split2.length == 2) return new InetSocketAddress(split2[1], Integer.parseInt(split[1])); throw new IllegalArgumentException("expected address in format '[/]
:port', got " + hostAddressPort); } public static void main(String[] args) { System.out.println(parseHostAddressPort("/127.0.0.1:1234")); System.out.println(parseHostAddressPort("localhost/127.0.0.1:1234")); System.out.println(parseHostAddressPort("127.0.0.1:1234")); System.out.println(parseHostAddressPort("localhost:1234")); } }