Java IP Address Get getIPAddress()

Here you can find the source of getIPAddress()

Description

Get the IP address of the host computer, or the loopback address (127.0.0.1) if the operation fails.

License

Open Source License

Return

the IP Address string.

Declaration

public static String getIPAddress() 

Method Source Code

//package com.java2s;
/*---------------------------------------------------------------
*  Copyright 2011 by the Radiological Society of North America
*
*  This source software is released under the terms of the
*  RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
*----------------------------------------------------------------*/

import java.net.*;

import java.util.*;

public class Main {
    static final String def = "127.0.0.1";

    /**//from w  w w .j  a v  a  2s . c  o  m
     * Get the IP address of the host computer, or the loopback address
     * (127.0.0.1) if the operation fails.
     * @return the IP Address string.
     */
    public static String getIPAddress() {
        try {
            //Get all the network interfaces
            Enumeration<NetworkInterface> nwEnum = NetworkInterface.getNetworkInterfaces();

            //Return the first IPv4 address that is not a loopback address.
            while (nwEnum.hasMoreElements()) {
                NetworkInterface nw = nwEnum.nextElement();
                Enumeration<InetAddress> ipEnum = nw.getInetAddresses();
                while (ipEnum.hasMoreElements()) {
                    InetAddress ina = ipEnum.nextElement();
                    if ((ina instanceof Inet4Address) && !ina.isLoopbackAddress()) {
                        return ina.getHostAddress();
                    }
                }
            }
        } catch (Exception ex) {
        }
        return def;
    }
}

Related

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