2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.protocol.util;
11 import com.google.common.collect.Lists;
12 import com.google.common.net.HostAndPort;
13 import java.net.InetSocketAddress;
14 import java.util.Arrays;
15 import java.util.List;
18 * Created as a util for test tools
20 public final class InetSocketAddressUtil {
21 private static final String SEPARATOR = ",";
23 private InetSocketAddressUtil() {
24 throw new UnsupportedOperationException();
27 public static List<InetSocketAddress> parseAddresses(final String address, final int defaultPort) {
28 return Lists.transform(Arrays.asList(address.split(SEPARATOR)), input -> getInetSocketAddress(input, defaultPort));
31 public static List<InetSocketAddress> parseAddresses(final String address) {
32 return Lists.transform(Arrays.asList(address.split(SEPARATOR)), input -> getInetSocketAddress(input, null));
35 public static HostAndPort toHostAndPort(final InetSocketAddress address) {
36 return HostAndPort.fromParts(address.getHostString(), address.getPort());
39 public static InetSocketAddress getInetSocketAddress(final String hostPortString, final Integer defaultPort) {
40 final HostAndPort hostAndPort = HostAndPort.fromString(hostPortString);
41 if (defaultPort != null) {
42 return new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPortOrDefault(defaultPort));
44 return new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort());
47 public static InetSocketAddress getRandomLoopbackInetSocketAddress(final int port) {
48 return new InetSocketAddress(getRandomLoopbackIpAddress(), port);
51 public static InetSocketAddress getRandomLoopbackInetSocketAddress() {
52 return getRandomLoopbackInetSocketAddress(getRandomPort());
56 * Generate a random high range port number
58 * @return A port number range from 10000 to 50000
60 public static int getRandomPort() {
61 final int randPort = 10000 + (int) Math.round(40000 * Math.random());
66 * Generate a random loopback ip address
67 * IP address range: 127.50.50.50 ~ 127.250.250.250
68 * We did not utilize the whole 127./8 range to avoid using common addresses like 127.0.0.1
69 * @return Generated random loopback IP address
71 public static String getRandomLoopbackIpAddress() {
72 final StringBuilder sb = new StringBuilder("127");
73 for (int i = 0; i < 3; i++) {
74 sb.append(".").append(50 + (int) Math.round(Math.random() * 200));