Java IP Address Get getFirstNonLoopBackAddress(boolean preferIpv4, boolean preferIPv6)

Here you can find the source of getFirstNonLoopBackAddress(boolean preferIpv4, boolean preferIPv6)

Description

get First Non Loop Back Address

License

Apache License

Declaration

public static String getFirstNonLoopBackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException 

Method Source Code


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

import java.net.*;
import java.util.Enumeration;

public class Main {
    public static String getFirstNonLoopBackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
        final Enumeration en = NetworkInterface.getNetworkInterfaces();

        while (en.hasMoreElements()) {
            final NetworkInterface i = (NetworkInterface) en.nextElement();

            for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
                final InetAddress address = (InetAddress) en2.nextElement();
                if (!address.isLoopbackAddress()) {
                    if (address instanceof Inet4Address) {
                        if (preferIPv6) {
                            continue;
                        }//  w  w  w .ja v a 2s.  co  m

                        return address.getHostAddress();
                    }
                    if (address instanceof Inet6Address) {
                        if (preferIpv4) {
                            continue;
                        }

                        return address.getHostAddress();
                    }
                }
            }
        }

        return null;
    }
}

Related

  1. getExternalIPAddress()
  2. getExternalIPAddress()
  3. getExternalIPAddress()
  4. getFirstLocalNonLoopbackIpAddress()
  5. getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6)
  6. getHostIp()
  7. getHostIp()
  8. getHostIP()
  9. getHostIP()