Java IP Address Get getIP()

Here you can find the source of getIP()

Description

Get an IP.

License

Creative Commons License

Exception

Parameter Description
SocketException an exception

Declaration

public static InetAddress getIP() throws SocketException 

Method Source Code


//package com.java2s;
/*/*from ww w.j a  v a2  s  . c  o  m*/
 * This work is licensed under the Creative Commons Attribution 3.0 Unported
 * License. To view a copy of this license, visit
 * http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative
 * Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
 */

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    private static InetAddress _ip;

    /**
     * Get an IP.
     *
     * @return
     * @throws SocketException
     */
    public static InetAddress getIP() throws SocketException {
        if (_ip != null) {
            return _ip;
        }

        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        NetworkInterface ni;
        while (nis.hasMoreElements()) {
            ni = nis.nextElement();
            if (!ni.isLoopback()/*not loopback*/ && ni.isUp()/*it works now*/) {
                for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                    //filter for ipv4/ipv6
                    if (ia.getAddress().getAddress().length == 4) {
                        //4 for ipv4, 16 for ipv6
                        _ip = ia.getAddress();
                        return _ip;
                    }
                }
            }
        }
        return null;
    }
}

Related

  1. getInternalIp()
  2. getInternalIp()
  3. getInternetIpAddress()
  4. getIntfFromLabelAdva(int n, Inet4Address ip)
  5. getIntranetIp()
  6. getIp()
  7. getIP()
  8. getIp()
  9. getIp()