Java Local Address Get getLocalNetAddress()

Here you can find the source of getLocalNetAddress()

Description

get Local Net Address

License

Open Source License

Declaration

public static InetAddress getLocalNetAddress() 

Method Source Code


//package com.java2s;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class Main {

    public static InetAddress getLocalNetAddress() {
        try {/*from   www . ja v a  2s .co  m*/
            return getNet4Address();
        } catch (Exception ex) {
        }

        return null;
    }

    private static InetAddress getNet4Address() throws UnknownHostException {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (inetAddress instanceof Inet4Address) {
                        if (!inetAddress.isLoopbackAddress()) {
                            return inetAddress;
                        }
                    }
                }
            }
        } catch (SocketException e) {
        }

        return InetAddress.getByName(null);
    }
}

Related

  1. getLocalAddrs()
  2. getLocalInet4Address()
  3. getLocalInet4Address()
  4. getLocalInternetProtocolAddress()
  5. getLocalMachineAddress()