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.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
    public static final String LOCALHOST = "127.0.0.1";
    public static final String ANYHOST = "0.0.0.0";

    public static InetAddress getLocalAddress() {
        InetAddress localAddress = null;
        try {//from  w  w w.j a  v  a 2  s  .  c  o  m
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                return localAddress;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = interfaces.nextElement();
                        Enumeration<InetAddress> addresses = network.getInetAddresses();
                        if (addresses != null) {
                            while (addresses.hasMoreElements()) {
                                try {
                                    InetAddress address = addresses.nextElement();
                                    if (isValidAddress(address)) {
                                        return address;
                                    }
                                } catch (Throwable e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return localAddress;
    }

    private static boolean isValidAddress(InetAddress address) {
        if (address == null || address.isLoopbackAddress())
            return false;
        String name = address.getHostAddress();
        return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name)
                && IP_PATTERN.matcher(name).matches());
    }
}

Related

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