Sunday 6 March 2022

Java: Get system ip address as string

Below snippet return the system IP address in textual presentation.

 

 


Find the below working application.

 

GetLocalIpAddress.java

package com.sample.app.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class GetLocalIpAddress {

    private static String getLocalAddressAsString() throws UnknownHostException, SocketException {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

        if (interfaces == null) {
            throw new UnknownHostException();
        }

        while (interfaces.hasMoreElements()) {
            Enumeration<InetAddress> inetAddesses = interfaces.nextElement().getInetAddresses();

            if (inetAddesses == null) {
                continue;
            }

            while (inetAddesses.hasMoreElements()) {
                InetAddress inetAddress = inetAddesses.nextElement();

                if (inetAddress == null) {
                    continue;
                }

                if (acceptableAddress(inetAddress)) {
                    return inetAddress.getHostAddress();
                }
            }
        }

        throw new UnknownHostException();

    }

    private static boolean acceptableAddress(InetAddress address) {
        return !address.isLoopbackAddress() && !address.isAnyLocalAddress() && !address.isLinkLocalAddress();
    }

    public static void main(String[] args) throws UnknownHostException, SocketException {
        System.out.println(getLocalAddressAsString());
    }

}




Previous                                                    Next                                                    Home

No comments:

Post a Comment