1 /*******************************************************************************
2 * Copyright (c) 2007, 2011 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.db.management.discovery;
14 import java.net.InetSocketAddress;
17 * @author Tuukka Lehtonen
19 public final class InetAddressUtils {
24 * @throws IllegalArgumentException
26 public static InetSocketAddress parse(String hostAndPort) throws IllegalArgumentException {
27 String[] split = hostAndPort.split(":");
28 if (split.length != 2)
29 throw new IllegalArgumentException("address does not contain a port, missing ':' character");
30 return new InetSocketAddress(split[0], Integer.parseInt(split[1]));
36 * @throws IllegalArgumentException
38 public static InetSocketAddress parseUnresolved(String hostAndPort) throws IllegalArgumentException {
39 String[] split = hostAndPort.split(":");
40 if (split.length != 2)
41 throw new IllegalArgumentException("address does not contain a port, missing ':' character");
42 return InetSocketAddress.createUnresolved(split[0], Integer.parseInt(split[1]));
45 public static String toHostString(InetSocketAddress address) {
46 if (address == null) return "null";
47 return address.getHostName() + ":" + address.getPort();
53 * @throws IllegalArgumentException
55 public static InetSocketAddress parseHostAddressPort(String hostAddressPort) throws IllegalArgumentException {
56 String[] split = hostAddressPort.split(":");
57 if (split.length != 2)
58 throw new IllegalArgumentException("address not in format '[<host>/]<address>:port', does not contain a port, missing ':' character: " + hostAddressPort);
59 String[] split2 = split[0].split("/");
60 if (split2.length == 1)
61 return new InetSocketAddress(split[0], Integer.parseInt(split[1]));
62 if (split2.length == 2)
63 return new InetSocketAddress(split2[1], Integer.parseInt(split[1]));
64 throw new IllegalArgumentException("expected address in format '[<host>/]<address>:port', got " + hostAddressPort);
67 public static void main(String[] args) {
68 System.out.println(parseHostAddressPort("/127.0.0.1:1234"));
69 System.out.println(parseHostAddressPort("localhost/127.0.0.1:1234"));
70 System.out.println(parseHostAddressPort("127.0.0.1:1234"));
71 System.out.println(parseHostAddressPort("localhost:1234"));