Java Local Address Get getLocalAddress()

Here you can find the source of getLocalAddress()

Description

get Local Address

License

Apache License

Declaration

public static InetAddress getLocalAddress() 

Method Source Code


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

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;

public class Main {
    public static InetAddress getLocalAddress() {
        try {//from   www  .j a  va2 s. c  o  m
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            ArrayList<Inet4Address> ipv4Result = new ArrayList<Inet4Address>();
            ArrayList<Inet6Address> ipv6Result = new ArrayList<Inet6Address>();
            while (enumeration.hasMoreElements()) {
                final NetworkInterface networkInterface = enumeration.nextElement();
                final Enumeration<InetAddress> en = networkInterface.getInetAddresses();
                while (en.hasMoreElements()) {
                    final InetAddress address = en.nextElement();
                    if (!address.isLoopbackAddress()) {
                        if (address instanceof Inet6Address) {
                            ipv6Result.add((Inet6Address) address);
                        }
                        if (address instanceof Inet4Address) {
                            ipv4Result.add((Inet4Address) address);
                        }
                    }
                }
            }

            // priority use ipv4
            if (!ipv4Result.isEmpty()) {
                for (Inet4Address ip : ipv4Result) {
                    String host = ip.getHostAddress();
                    if (host.startsWith("127") || host.startsWith("192")) {
                        continue;
                    }
                    return ip;
                }
                // if all fail,return last one.
                return ipv4Result.get(ipv4Result.size() - 1);
            }
            // ipv6
            else if (!ipv6Result.isEmpty()) {
                return ipv6Result.get(0);
            }
            // All fail,use localhost. (:
            final InetAddress localHost = InetAddress.getLocalHost();
            return localHost;
        } catch (SocketException | UnknownHostException e) {
            // Log
            return InetAddress.getLoopbackAddress();
        }
    }
}

Related

  1. getLocalAddr()
  2. getLocalAddress()
  3. getLocalAddress()
  4. getLocalAddress()
  5. getLocalAddress()
  6. getLocalAddress()
  7. getLocalAddress()
  8. getLocalAddress()
  9. getLocalAddress()