All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.emc.mongoose.api.common.net.NetUtil Maven / Gradle / Ivy

There is a newer version: 4.0.0-alpha5
Show newest version
package com.emc.mongoose.api.common.net;

import com.emc.mongoose.api.common.exception.OmgDoesNotPerformException;
import com.emc.mongoose.api.common.exception.OmgLookAtMyConsoleException;

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

/**
 Created by kurila on 11.07.16.
 */
public interface NetUtil {

	/**
	 Tries to resolve 1st enabled external network interface IP address.
	 Tries to fall back to loopback interface if no valid external interface found.
	 @return IP address
	 @throws OmgLookAtMyConsoleException if failed to resolve an interface address
	 @throws OmgDoesNotPerformException
	 */
	static InetAddress getHostAddr()
	throws OmgLookAtMyConsoleException, OmgDoesNotPerformException {
		InetAddress addr = null;
		final Enumeration netIfaces;
		try {
			netIfaces = NetworkInterface.getNetworkInterfaces();
		} catch(final SocketException e) {
			throw new OmgLookAtMyConsoleException(e);
		}
		NetworkInterface nextNetIface;
		while(netIfaces.hasMoreElements()) {
			nextNetIface = netIfaces.nextElement();
			try {
				if(!nextNetIface.isLoopback() && nextNetIface.isUp()) {
					final Enumeration addrs = nextNetIface.getInetAddresses();
					while(addrs.hasMoreElements()) {
						addr = addrs.nextElement();
						if(Inet4Address.class.isInstance(addr)) {
							// resolved the external interface address
							break;
						}
					}
				}
			} catch(final SocketException e) {
				throw new OmgLookAtMyConsoleException(e);
			}
		}

		if(addr == null) {
			addr = InetAddress.getLoopbackAddress();
		}

		if(addr == null) {
			throw new OmgDoesNotPerformException("");
		}
		return addr;
	}


	static String getHostAddrString()
	throws OmgDoesNotPerformException, OmgLookAtMyConsoleException {
		return getHostAddr().getHostAddress();
	}

	static long getHostAddrCode()
	throws OmgDoesNotPerformException, OmgLookAtMyConsoleException {
		return getHostAddrString().hashCode();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy