Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

import java.util.Enumeration;

public class Main {

    public static String getLocalIpAddress() {
        try {
            Enumeration<NetworkInterface> networkInfo = NetworkInterface.getNetworkInterfaces();
            for (Enumeration<NetworkInterface> en = networkInfo; en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                Enumeration<InetAddress> intfAddress = intf.getInetAddresses();
                for (Enumeration<InetAddress> enumIpAddr = intfAddress; enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {

        }
        return null;
    }
}