Java Local Address Get getLocalInet4Address()

Here you can find the source of getLocalInet4Address()

Description

Returns the IPv4 address of the local host.

License

Apache License

Return

the IPv4 address of the local host reachable from other hosts in the same network.

Declaration

public static InetAddress getLocalInet4Address() throws SocketException 

Method Source Code


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

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

import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    /**//from  w  ww . j  a  va  2  s  .c  o  m
     * Returns the IPv4 address of the local host. The returned address is not the loopback address.
     * @return the IPv4 address of the local host reachable from other hosts in the same network.
     */
    public static InetAddress getLocalInet4Address() throws SocketException {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface current = interfaces.nextElement();
            //System.out.println(current);
            if (!current.isUp() || current.isLoopback() || current.isVirtual())
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr.isLoopbackAddress())
                    continue;
                if (current_addr instanceof Inet4Address)
                    return current_addr;
            }
        }
        return null;
    }
}

Related

  1. getLocalAddresses()
  2. getLocalAddressFromNetworkInterfacesListeningOnPort(int pPort)
  3. getLocalAddressStrings()
  4. getLocalAddressWithMulticast()
  5. getLocalAddrs()
  6. getLocalInet4Address()
  7. getLocalInternetProtocolAddress()
  8. getLocalMachineAddress()
  9. getLocalNetAddress()