Java IP Address Get getLocalIP()

Here you can find the source of getLocalIP()

Description

get Local IP

License

Open Source License

Declaration

public static String getLocalIP() 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 EURA NOVA./*from  w w  w  .  ja v a 2  s.co  m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Aldemar Reynaga - initial API and implementation
 *     Salim Jouili - initial API and implementation
 ******************************************************************************/

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class Main {
    public static String getLocalIP() {

        String ipOnly = "";
        try {
            Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
            if (nifs == null)
                return "";
            while (nifs.hasMoreElements()) {
                NetworkInterface nif = nifs.nextElement();
                // We ignore subinterfaces - as not yet needed.

                if (!nif.isLoopback() && nif.isUp() && !nif.isVirtual()) {
                    Enumeration<InetAddress> adrs = nif.getInetAddresses();
                    while (adrs.hasMoreElements()) {
                        InetAddress adr = adrs.nextElement();
                        if (adr != null && !adr.isLoopbackAddress()
                                && (nif.isPointToPoint() || !adr.isLinkLocalAddress())) {
                            String adrIP = adr.getHostAddress();
                            String adrName;
                            if (nif.isPointToPoint()) // Performance issues getting hostname for mobile internet sticks
                                adrName = adrIP;
                            else
                                adrName = adr.getCanonicalHostName();

                            if (!adrName.equals(adrIP))
                                return adrIP;
                            else
                                ipOnly = adrIP;
                        }
                    }
                }
            }
            return ipOnly;
        } catch (SocketException ex) {
            return "";
        }
    }
}

Related

  1. getLocalIp()
  2. getLocalIp()
  3. getLocalIP()
  4. getLocalIP()
  5. getLocalIP()
  6. getLocalIp()
  7. getLocalIp(final boolean useIpv6)
  8. getLocalIPAddress()
  9. getLocalIPAddress()