Java IP Address Get getIpAddress()

Here you can find the source of getIpAddress()

Description

Return a non loopback IPv4 address for the machine running this process.

License

Apache License

Return

non loopback IPv4 address for the machine running this process

Declaration

public static String getIpAddress() 

Method Source Code


//package com.java2s;
/*//  www . j a v  a2s. c  om
 * Copyright 2013-2014 the original author or authors.
 *
 * 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.io.IOException;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;

import java.util.Enumeration;

public class Main {
    /**
     * Return a non loopback IPv4 address for the machine running this process.
     * If the machine has multiple network interfaces, the IP address for the
     * first interface returned by {@link java.net.NetworkInterface#getNetworkInterfaces}
     * is returned.
     *
     * @return non loopback IPv4 address for the machine running this process
     *
     * @see java.net.NetworkInterface#getNetworkInterfaces
     * @see java.net.NetworkInterface#getInetAddresses
     */
    public static String getIpAddress() {
        try {
            for (Enumeration<NetworkInterface> enumNic = NetworkInterface.getNetworkInterfaces(); enumNic
                    .hasMoreElements();) {
                NetworkInterface ifc = enumNic.nextElement();
                if (ifc.isUp()) {
                    for (Enumeration<InetAddress> enumAddr = ifc.getInetAddresses(); enumAddr.hasMoreElements();) {
                        InetAddress address = enumAddr.nextElement();
                        if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
                            return address.getHostAddress();
                        }
                    }
                }
            }
        } catch (IOException e) {
            // ignore
        }

        return "unknown";
    }
}

Related

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