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() 

Method Source Code

//package com.java2s;
/*//  w w w .j  a v  a  2s  .  c  om
 * Copyright 2002-2005 the original author or authors.
 *
 * 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.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;

public class Main {

    public static String getLocalIp() {
        String localIp = "";

        try {
            localIp = InetAddress.getLocalHost().getHostAddress();
            if ("/".equals(System.getProperties().getProperty("file.separator"))) {
                Enumeration<?> netInterfaces = NetworkInterface.getNetworkInterfaces();
                InetAddress ip = null;
                while (netInterfaces.hasMoreElements()) {
                    NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                    //if(ni.getName().equals("eth0")) {
                    Enumeration<?> e2 = ni.getInetAddresses();
                    while (e2.hasMoreElements()) {
                        ip = (InetAddress) e2.nextElement();
                        if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                                && ip.getHostAddress().indexOf(":") == -1) {
                            localIp = ip.getHostAddress();
                            break;
                        } else {
                            continue;
                        }
                    }
                    //}
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return localIp;
    }
}

Related

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