summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/net/LinuxInetAddress.java
blob: 34a7a9b9c6e42b73ed36e3aac8e57b1f0f1a8647 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.net;

import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * Utilities for returning localhost addresses on Linux.
 * See
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037
 * on why this is necessary.
 *
 * @author bratseth
 */
public class LinuxInetAddress {

    private static Logger log = Logger.getLogger(LinuxInetAddress.class.getName());

    /**
     * Returns an InetAddress representing the address of the localhost.
     * A non-loopback address is preferred if available.
     * An address that resolves to a hostname is preferred among non-loopback addresses.
     * IPv4 is preferred over IPv6 among resolving addresses.
     *
     * @return a localhost address
     */
    public static InetAddress getLocalHost() {
        InetAddress fallback = InetAddress.getLoopbackAddress();
        try {
            InetAddress localAddress = InetAddress.getLocalHost();
            fallback = localAddress;
            List<InetAddress> nonLoopback =
                getAllLocalFromNetwork().stream().filter(a -> ! a.isLoopbackAddress()).collect(Collectors.toList());
            if (nonLoopback.isEmpty()) {
                return fallback;
            }
            fallback = nonLoopback.get(0);
            List<InetAddress> resolving =
                    nonLoopback.stream().filter(a -> doesResolve(a)).collect(Collectors.toList());
            if (resolving.isEmpty()) {
                return fallback;
            }
            fallback = resolving.get(0);
            List<InetAddress> ipV4 =
                    resolving.stream().filter(a -> a instanceof Inet4Address).collect(Collectors.toList());
            if (ipV4.isEmpty()) {
                return fallback;
            }
            return ipV4.get(0);
        } catch (UnknownHostException e) {
            return fallback;
        }
    }

    /**
     * Returns all local addresses of this host.
     *
     * @return an array of the addresses of this
     * @throws UnknownHostException if we cannot access the network
     */
    public static InetAddress[] getAllLocal() throws UnknownHostException {
        InetAddress[] localInetAddresses = InetAddress.getAllByName("127.0.0.1");
        if ( ! localInetAddresses[0].isLoopbackAddress()) return localInetAddresses;
        return getAllLocalFromNetwork().toArray(new InetAddress[0]);
    }

    /**
     * Returns all local addresses of this host.
     *
     * @return a list of the addresses of this
     * @throws UnknownHostException if we cannot access the network
     */
    private static List<InetAddress> getAllLocalFromNetwork() throws UnknownHostException {
        try {
            List<InetAddress> addresses = new ArrayList<>();
            for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces()))
                addresses.addAll(Collections.list(networkInterface.getInetAddresses()));
            return addresses;
        }
        catch (SocketException ex) {
            throw new UnknownHostException("127.0.0.1");
        }
    }

    private static boolean doesResolve(InetAddress addr) {
        String asAddr = addr.getHostAddress();
        String asName = addr.getCanonicalHostName();
        return ! asAddr.equals(asName);
    }

}