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

info.unterrainer.commons.opcuabrowser.tests.HostnameUtil Maven / Gradle / Ivy

The newest version!
package info.unterrainer.commons.opcuabrowser.tests;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.LoggerFactory;

public class HostnameUtil {

	/**
	 * @return the local hostname, if possible. Failure results in "localhost".
	 */
	public static String getHostname() {
		try {
			return InetAddress.getLocalHost().getHostName();
		} catch (UnknownHostException e) {
			return "localhost";
		}
	}

	/**
	 * Given an address resolve it to as many unique addresses or hostnames as can
	 * be found.
	 *
	 * @param address the address to resolve.
	 * @return the addresses and hostnames that were resolved from {@code address}.
	 */
	public static Set getHostnames(final String address) {
		return getHostnames(address, true);
	}

	/**
	 * Given an address resolve it to as many unique addresses or hostnames as can
	 * be found.
	 *
	 * @param address         the address to resolve.
	 * @param includeLoopback if {@code true} loopback addresses will be included in
	 *                        the returned set.
	 * @return the addresses and hostnames that were resolved from {@code address}.
	 */
	public static Set getHostnames(final String address, final boolean includeLoopback) {
		Set hostnames = new HashSet<>();

		try {
			InetAddress inetAddress = InetAddress.getByName(address);

			if (inetAddress.isAnyLocalAddress()) {
				try {
					Enumeration nis = NetworkInterface.getNetworkInterfaces();

					for (NetworkInterface ni : Collections.list(nis)) {
						Collections.list(ni.getInetAddresses()).forEach(ia -> {
							if (ia instanceof Inet4Address) {
								boolean loopback = ia.isLoopbackAddress();

								if (!loopback || includeLoopback) {
									hostnames.add(ia.getHostName());
									hostnames.add(ia.getHostAddress());
									hostnames.add(ia.getCanonicalHostName());
								}
							}
						});
					}
				} catch (SocketException e) {
					LoggerFactory.getLogger(HostnameUtil.class).warn("Failed to NetworkInterfaces for bind address: {}",
							address, e);
				}
			} else {
				boolean loopback = inetAddress.isLoopbackAddress();

				if (!loopback || includeLoopback) {
					hostnames.add(inetAddress.getHostName());
					hostnames.add(inetAddress.getHostAddress());
					hostnames.add(inetAddress.getCanonicalHostName());
				}
			}
		} catch (UnknownHostException e) {
			LoggerFactory.getLogger(HostnameUtil.class).warn("Failed to get InetAddress for bind address: {}", address,
					e);
		}

		return hostnames;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy