Java IP Address Get getLocalIp(final boolean useIpv6)

Here you can find the source of getLocalIp(final boolean useIpv6)

Description

get Local Ip

License

Apache License

Declaration

public static String getLocalIp(final boolean useIpv6) 

Method Source Code


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

import java.net.*;
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static String getLocalIp(final String interfaceName, final boolean useIpv6) {
        try {/* w  ww  .ja v  a  2s.co  m*/
            final NetworkInterface netInterface = NetworkInterface.getByName(interfaceName);
            final ArrayList<InetAddress> addresses = Collections.list(netInterface.getInetAddresses());

            for (final InetAddress address : addresses) {
                if (address instanceof Inet4Address && !useIpv6) {
                    return address.getHostAddress();
                } else if (address instanceof Inet6Address && useIpv6) {
                    return address.getHostAddress();
                }
            }
        } catch (final SocketException e) {
            throw new IllegalStateException(e);
        }
        throw new IllegalStateException("no suitable local address found");
    }

    public static String getLocalIp(final boolean useIpv6) {
        try {
            final ArrayList<NetworkInterface> networkInterfaces = Collections
                    .list(NetworkInterface.getNetworkInterfaces());
            for (final NetworkInterface netInterface : networkInterfaces) {
                if (!netInterface.isLoopback() && !netInterface.isPointToPoint()) {
                    final ArrayList<InetAddress> addresses = Collections.list(netInterface.getInetAddresses());
                    for (final InetAddress address : addresses) {
                        if (address instanceof Inet4Address && !useIpv6) {
                            return address.getHostAddress();
                        } else if (address instanceof Inet6Address && useIpv6) {
                            return address.getHostAddress();
                        }
                    }
                }
            }
        } catch (final SocketException e) {
            throw new IllegalStateException(e);
        }
        throw new IllegalStateException("no suitable local address found");
    }
}

Related

  1. getLocalIp()
  2. getLocalIP()
  3. getLocalIp()
  4. getLocalIP()
  5. getLocalIp()
  6. getLocalIPAddress()
  7. getLocalIPAddress()
  8. getLocalIpAddress()
  9. getLocalIPAddress()