Java IP Address Get getLocalIP()

Here you can find the source of getLocalIP()

Description

Get a local IP for remote access.

License

Apache License

Exception

Parameter Description
SocketException an exception

Return

A local IP address.

Declaration

static public InetAddress getLocalIP() throws SocketException 

Method Source Code

//package com.java2s;
/*/*w  ww .ja va2s. c  om*/
 * Copyright (C) IBM Corp. 2009.
 * 
 * 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.util.Enumeration;

public class Main {
    /**
     * Get a local IP for remote access. Used to setup communication between job controller and Mapper/Reducer.
     * @return A local IP address.
     * @throws SocketException
     */
    static public InetAddress getLocalIP() throws SocketException {
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface
                .getNetworkInterfaces();

        InetAddress ip = null;
        InetAddress localip = null;

        while (netInterfaces.hasMoreElements()) {
            NetworkInterface netIntf = netInterfaces.nextElement();

            Enumeration<InetAddress> address = netIntf.getInetAddresses();

            while (address.hasMoreElements()) {
                ip = address.nextElement();

                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {
                    return ip;
                } else if (ip.isSiteLocalAddress()
                        && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {
                    localip = ip;
                }
            }
        }

        return localip;
    }
}

Related

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