Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

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

public class Main {
    public static String getLocalIpAddress() throws Exception {
        String ipAddress = null;

        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

        while (en.hasMoreElements()) {
            NetworkInterface e = en.nextElement();
            Enumeration<InetAddress> addresses = e.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (!address.isLoopbackAddress() && address.isSiteLocalAddress()) {
                    ipAddress = address.getHostName();
                    break;
                }
            }
        }

        if (ipAddress == null) {
            ipAddress = InetAddress.getLocalHost().getHostAddress();
        }

        return ipAddress;
    }
}