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;
16 import java.util.stream.Collectors;
19 * Created as a util for test tools.
21 public final class InetSocketAddressUtil {
22 private static final String SEPARATOR = ",";
24 private InetSocketAddressUtil() {
25 throw new UnsupportedOperationException();
28 public static List<InetSocketAddress> parseAddresses(final String address, final int defaultPort) {
29 return Arrays.asList(address.split(SEPARATOR)).stream()
30 .map(input -> getInetSocketAddress(input, defaultPort)).collect(Collectors.toList());
33 public static List<InetSocketAddress> parseAddresses(final String address) {
34 return Lists.transform(Arrays.asList(address.split(SEPARATOR)), input -> getInetSocketAddress(input, null));
37 public static HostAndPort toHostAndPort(final InetSocketAddress address) {
38 return HostAndPort.fromParts(address.getHostString(), address.getPort());
41 public static InetSocketAddress getInetSocketAddress(final String hostPortString, final Integer defaultPort) {
42 final HostAndPort hostAndPort = HostAndPort.fromString(hostPortString);
43 if (defaultPort != null) {
44 return new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPortOrDefault(defaultPort));
46 return new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPort());
49 public static InetSocketAddress getRandomLoopbackInetSocketAddress(final int port) {
50 return new InetSocketAddress(getRandomLoopbackIpAddress(), port);
53 public static InetSocketAddress getRandomLoopbackInetSocketAddress() {
54 return getRandomLoopbackInetSocketAddress(getRandomPort());
58 * Generate a random high range port number.
60 * @return A port number range from 20000 to 60000
62 public static int getRandomPort() {
63 return 20000 + (int) Math.round(40000 * Math.random());
67 * Generate a random loopback ip address.
68 * IP address range: 127.50.50.50 ~ 127.250.250.250
69 * We did not utilize the whole 127./8 range to avoid using common addresses like 127.0.0.1
71 * @return Generated random loopback IP address
73 public static String getRandomLoopbackIpAddress() {
74 final StringBuilder sb = new StringBuilder("127");
75 for (int i = 0; i < 3; i++) {
76 sb.append(".").append(50 + (int) Math.round(Math.random() * 200));