Java InetAddress Create getLocalInetAddress()

Here you can find the source of getLocalInetAddress()

Description

Returns an IP address of the device to be used for local communication on the subnet.

License

Apache License

Return

the selected IP address or null if no valid IP addresses had been found.

Declaration

public static InetAddress getLocalInetAddress() 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    /**/*w ww.  j  a  v  a  2  s .c o m*/
     * Returns an IP address of the device to be used for local communication on the subnet.
     * Order of preference for selecting addresses:
     * 1) IPv6 link local
     * 2) IPv6 global address
     * 3) IPv4 address
     * 
     * @return the selected IP address or null if no valid IP addresses had been found.
     */
    public static InetAddress getLocalInetAddress() {
        try {
            List<InetAddress> addresses = getIPAddresses();
            for (InetAddress a : addresses) {
                if (a instanceof Inet6Address && a.isLinkLocalAddress()) {
                    return a;
                }
            }
            for (InetAddress a : addresses) {
                if (a instanceof Inet6Address) {
                    return a;
                }
            }
            if (addresses.size() > 0) {
                return addresses.get(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * List all IP addresses of the device, except loopback addresses.
     * 
     * @return a List of IP addresses
     * @throws IOException
     */
    public static List<InetAddress> getIPAddresses() throws IOException {
        List<InetAddress> addresses = new ArrayList<InetAddress>();
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress a : addrs) {
                if (a.isLoopbackAddress()) {
                    continue;
                }
                addresses.add(a);
            }
        }
        return addresses;
    }
}

Related

  1. getIPAsLong(InetAddress address)
  2. getIPAsString(InetAddress addr)
  3. getIPv4LocalNetMask(InetAddress ip, int netPrefix)
  4. getIPv6InetAddresses(NetworkInterface networkInterface)
  5. getLocalInetAddress()
  6. getLocalInetAddress()
  7. getLocalInetAddress(String host)
  8. getLocalInetAddress(String host)
  9. getLocalInetAddresses()