30bc8d823f6b140ae5c03ba5335755a5d54b8fad
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.testsuites.integration.context.utils;
23
24 import java.net.InetAddress;
25 import java.net.NetworkInterface;
26 import java.net.SocketException;
27 import java.util.Collections;
28 import java.util.Enumeration;
29 import java.util.SortedSet;
30 import java.util.TreeSet;
31
32 /**
33  * The Class NetworkUtils contains some utility functions for getting network information for context tests.
34  */
35 public class NetworkUtils {
36
37     /**
38      * Instantiates a new network utils.
39      */
40     private NetworkUtils() {
41         // Private constructor to block subclassing
42     }
43
44     /**
45      * The JGroups IP address must be set to a real (not loopback) IP address for Infinispan to work. In order to ensure
46      * that all the JVMs in a test pick up the same IP address, this function sets the address to be the first
47      * non-loopback IPv4 address on a host
48      *
49      * @return Set of IPv4 addresses
50      * @throws SocketException throw socket exception if error occurs
51      */
52     public static SortedSet<String> getIPv4NonLoopAddresses() throws SocketException {
53         final TreeSet<String> ipAddressSet = new TreeSet<>();
54
55         final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
56         for (final NetworkInterface netint : Collections.list(nets)) {
57             final Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
58             for (final InetAddress inetAddress : Collections.list(inetAddresses)) {
59                 // Look for real IPv4 internet addresses
60                 if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) {
61                     ipAddressSet.add(inetAddress.getHostAddress());
62                 }
63             }
64         }
65         return ipAddressSet;
66     }
67
68 }