Java IP Address Get getIPAddress()

Here you can find the source of getIPAddress()

Description

Determins the IP address of the machine Kettle is running on.

License

Apache License

Return

The IP address

Declaration

public static final String getIPAddress() throws Exception 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.net.InetAddress;

import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    /**//from  ww w. java 2 s  . c o  m
     * Determins the IP address of the machine Kettle is running on.
     * 
     * @return The IP address
     */
    public static final String getIPAddress() throws Exception {
        Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumInterfaces.hasMoreElements()) {
            NetworkInterface nwi = (NetworkInterface) enumInterfaces.nextElement();
            Enumeration<InetAddress> ip = nwi.getInetAddresses();
            while (ip.hasMoreElements()) {
                InetAddress in = (InetAddress) ip.nextElement();
                if (!in.isLoopbackAddress() && in.toString().indexOf(":") < 0) {
                    return in.getHostAddress();
                }
            }
        }
        return "127.0.0.1";
    }

    /**
     * Get the primary IP address tied to a network interface (excluding
     * loop-back etc)
     * 
     * @param networkInterfaceName
     *            the name of the network interface to interrogate
     * @return null if the network interface or address wasn't found.
     * 
     * @throws SocketException
     *             in case of a security or network error
     */
    public static final String getIPAddress(String networkInterfaceName) throws SocketException {
        NetworkInterface networkInterface = NetworkInterface.getByName(networkInterfaceName);
        Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses();
        while (ipAddresses.hasMoreElements()) {
            InetAddress inetAddress = (InetAddress) ipAddresses.nextElement();
            if (!inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf(":") < 0) {
                String hostname = inetAddress.getHostAddress();
                return hostname;
            }
        }
        return null;
    }
}

Related

  1. getIpAddress()
  2. getIPAddress()
  3. getIpAddress()
  4. getIpAddress()
  5. getIPAddress()
  6. getIpAddress()
  7. getIPAddress()
  8. getIPAddress(boolean useIPv4)
  9. getIPAddress(final String hostName)