Java IP Address Get getLocalIP()

Here you can find the source of getLocalIP()

Description

get Local IP

License

Apache License

Declaration

public static String getLocalIP() throws Exception 

Method Source Code

//package com.java2s;
/**//from  w  w w .  j a  v a 2s. c o  m
 * Copyright (C) 2016 - 2017 youtongluan.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    private static String localIp = null;

    public static String getLocalIP() throws Exception {
        if (localIp != null) {
            return localIp;
        }
        Enumeration<?> e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces();
        while (e1.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) e1.nextElement();
            if (!isUp(ni)) {
                continue;
            }
            Enumeration<?> e2 = ni.getInetAddresses();
            while (e2.hasMoreElements()) {
                InetAddress ia = (InetAddress) e2.nextElement();
                if (isValid(ia)) {
                    localIp = ia.getHostAddress();
                    return localIp;
                }
            }
        }
        localIp = InetAddress.getLocalHost().getHostAddress().toString();
        return localIp;
    }

    private static boolean isUp(NetworkInterface ni) throws SocketException {
        return ni.getName().startsWith("eth") && (!ni.isVirtual()) && ni.isUp();
    }

    private static boolean isValid(InetAddress ia) {
        if (ia instanceof Inet6Address) {
            return false;
        }

        return ia.isSiteLocalAddress();

    }
}

Related

  1. getLocalHostIPAdress()
  2. getLocalHostIps()
  3. getLocalHostIps()
  4. getLocalIp()
  5. getLocalIp()
  6. getLocalIP()
  7. getLocalIP()
  8. getLocalIP()
  9. getLocalIp()