`

获取IP地址

    博客分类:
  • java
 
阅读更多
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

public class IPUtils {

	static final Logger logger = LoggerFactory.getLogger(IPUtils.class);

	private static String localAddress = null;

	/**
	 * <pre>
	 * 获取本机IPV4地址
	 * </pre>
	 *
	 * @return 如果无法获取 IP ips size为0
	 * @throws SocketException
	 */
	public static List<String> getIpAddress() {

		List<String> ips = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()) {
				NetworkInterface networkInterface = interfaces.nextElement();
				if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
					continue;
				}

				Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					InetAddress ipv4 = addresses.nextElement();
					if (ipv4 instanceof Inet4Address) {
						ips.add(ipv4.toString().replace("/", ""));
					}
				}
			}
		} catch (Exception e) {
			logger.error("Get local IP error|{}", e.getMessage(), e);
		}

		logger.info("server ip|{}", ips);
		return ips;

	}

	public static String getLocalAddress() {
		if (!StringUtils.isEmpty(localAddress)) {
			return localAddress;
		}

		List<String> ips = getIpAddress();
		if (CollectionUtils.isEmpty(ips)) {
			throw new RuntimeException("localAddress no found!");
		}

		return localAddress = ips.get(0);
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics