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.util.Iterator;
import java.net.NetworkInterface;
import java.net.InetAddress;

import java.util.regex.Pattern;
import java.net.InterfaceAddress;

public class Main {
    private static Pattern ipv4Pattern = Pattern.compile(
            "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){0,3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");

    public static InterfaceAddress getInterfaceAddress(NetworkInterface intf) {
        try {
            InterfaceAddress res = null;
            for (Iterator<InterfaceAddress> iterIntAddr = intf.getInterfaceAddresses().iterator(); iterIntAddr
                    .hasNext();) {
                InterfaceAddress intAddress = iterIntAddr.next();
                if (!intAddress.getAddress().isLoopbackAddress()) {
                    if (isIpv4(intAddress.getAddress()))
                        return intAddress;
                    else
                        res = intAddress;
                }
            }
            if (res != null)
                return res;
        } catch (Exception e) {
        }

        return null;
    }

    public static boolean isIpv4(InetAddress addr) {
        return ipv4Pattern.matcher(addr.getHostAddress().toString()).matches();
    }
}