Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static Pattern ipAddrPattern = Pattern.compile("(\\d+)\\.(\\d+\\.){2}\\d+");

    public static String findAppropriateIp() {
        String result = "unknown";

        Enumeration<NetworkInterface> e;
        try {
            e = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e1) {
            return result;
        }
        while (e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration<InetAddress> ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress inetAddr = ee.nextElement();
                String ipAddr = inetAddr.getHostAddress();

                Matcher m = ipAddrPattern.matcher(ipAddr);
                if (m.matches()) {
                    if (!m.group(1).equals("127")) {
                        result = ipAddr;
                    }
                }
            }
        }

        return result;
    }
}