Java IP Address Get getIPAddress(boolean useIPv4)

Here you can find the source of getIPAddress(boolean useIPv4)

Description

Get IP address from first non-localhost interface

License

Apache License

Parameter

Parameter Description
ipv4 true=return ipv4, false=return ipv6

Return

address or empty string

Declaration

public static String getIPAddress(boolean useIPv4) 

Method Source Code

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

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

public class Main {
    /**/*from   w w  w .java2 s .  co m*/
     * Get IP address from first non-localhost interface
     * @param ipv4  true=return ipv4, false=return ipv6
     * @return  address or empty string
     */
    public static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        if (addr instanceof Inet4Address) {
                            if (useIPv4)
                                return sAddr;
                        } else {
                            if (!useIPv4) {
                                int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                                return delim < 0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
        } // for now eat exceptions
        return "";
    }
}

Related

  1. getIpAddress()
  2. getIpAddress()
  3. getIPAddress()
  4. getIpAddress()
  5. getIPAddress()
  6. getIPAddress(final String hostName)
  7. getIPAddress(NetworkInterface e)
  8. getIPAddress(String hostname)
  9. getIpAddress(String server)