Java IP Address Get getIPAddress()

Here you can find the source of getIPAddress()

Description

This function is used to get IP Address of the host machine.

License

Open Source License

Return

ipadress of the host machine

Declaration

public static String getIPAddress() 

Method Source Code


//package com.java2s;
/*//from w  w  w  . ja v a 2 s. c o m
 * Copyright (c) 2016 Abhilash Kumar and Saurav Kumar.
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.net.*;
import java.util.Enumeration;

public class Main {
    /**
     * This function is used to get IP Address of the host machine. For chariot-server,
     * it is very likely (only possibility in dev) that it is connected by eth0 or by wlan0.
     * In that order, if an IP Address is found, it is returned. Not very certain of it's reliability.
     * @return ipadress of the host machine
     */
    public static String getIPAddress() {
        try {
            final NetworkInterface niEth0 = NetworkInterface.getByName("eth0");
            final NetworkInterface niWlan0 = NetworkInterface.getByName("wlan0");
            if (niEth0 != null) {
                for (Enumeration en = niEth0.getInetAddresses(); en.hasMoreElements();) {
                    final InetAddress addr = (InetAddress) en.nextElement();
                    if (addr instanceof Inet4Address) {
                        return addr.getHostAddress();
                    }
                }
            }
            if (niWlan0 != null) {
                for (Enumeration en = niWlan0.getInetAddresses(); en.hasMoreElements();) {
                    final InetAddress addr = (InetAddress) en.nextElement();
                    if (addr instanceof Inet4Address) {
                        return addr.getHostAddress();
                    }
                }
            }
        } catch (SocketException ignore) {
        }
        return "";
    }
}

Related

  1. getIP()
  2. getIp()
  3. getIP()
  4. getIp()
  5. getIpAddress()
  6. getIpAddress()
  7. getIpAddress()
  8. getIpAddress()
  9. getIpAddress()