get ip in java

Get IP address with multiple network interfaces

package getip;

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


import java.util.regex.Pattern;

public class Test {
    private static final Pattern IP_PATTERN       = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
    private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$");
    public static final String   ANYHOST          = "0.0.0.0";
    public static final String   LOCALHOST        = "127.0.0.1";

    private static boolean isValidAddress(InetAddress address) {
        if (address == null || address.isLoopbackAddress()) return false;
        String name = address.getHostAddress();
        return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches());
    }

    public static boolean isLocalHost(String host) {
        return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() || host.equalsIgnoreCase("localhost"));
    }

    public static boolean isAnyHost(String host) {
        return "0.0.0.0".equals(host);
    }

	private static volatile InetAddress LOCAL_ADDRESS = null;

	/**
	 * 遍历本地网卡,返回内网IP。
	 * 
	 * @return 本地网卡IP
	 */
	public static InetAddress getLocalAddress() {
		if (LOCAL_ADDRESS != null) {
			return LOCAL_ADDRESS;
		}
		InetAddress localAddress = getLocalAddress0();
		LOCAL_ADDRESS = localAddress;
		return localAddress;
	}

	private static InetAddress getLocalAddress0() {
		InetAddress localAddress = null;
        try {
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                return localAddress;
            }
        } catch (Throwable e) {
        	System.out.println("Failed to retriving ip address, " + e.getMessage());
        }
        
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				NetworkInterface network = interfaces.nextElement();
				System.out.println("------------------------");
				System.out.println("network interface: " + network.getDisplayName()
						            + "," + network.getName());				

				Enumeration<InetAddress> addresses = network.getInetAddresses();
				while (addresses != null && addresses.hasMoreElements()) {
					InetAddress address = addresses.nextElement();
					if (address == null) continue;
					
					System.out.println("------------------------");
					System.out.println("addr: " + address.getHostAddress());
					System.out.println("name: " + address.getHostName());
					if (address.isLoopbackAddress()) continue;
					
					String name = address.getHostAddress();
					if (name != null && name.startsWith("192.168")) {
						return address;
					}
				}
			}
		} catch (SocketException e) {
			throw new RuntimeException(e);
		}
		throw new RuntimeException("Could not get local host ip address!");
	}

	public static void main(String[] args) {
		System.out.println("get local ip: " + getip.Test.getLocalAddress().getHostAddress());
	}
}

猜你喜欢

转载自201310211952.iteye.com/blog/2219303