首页

实现常用IPUtils工具类来获取getMac本地mac地址、外网内网ip地址等代码示例

标签:IPUtils,ip工具类,getMac,mac地址,外网ip,内网ip,getIp     发布时间:2018-08-02   

一、前言

通过java.net.InetAddress、java.net.NetworkInterface获取getMac本地计算机内网mac地址(优先第一个)、获取getIp地址(优先外网再内网),详情参见代码示例。

二、代码示例

import java.net.InetAddress;@b@import java.net.NetworkInterface;@b@import java.util.Enumeration;@b@@b@public class IPUtils {@b@	@b@	public static String getMac() {@b@		String ret = null; // 优先内网, 优先第一个@b@		try {  @b@			Enumeration<NetworkInterface> netInterfaces = NetworkInterface  @b@					.getNetworkInterfaces();  @b@			InetAddress ip = null;  @b@			while (netInterfaces.hasMoreElements()) {  @b@				NetworkInterface ni = netInterfaces.nextElement(); @b@				Enumeration<InetAddress> address = ni.getInetAddresses(); @b@				if (ni.getHardwareAddress() != null) {@b@					while (address.hasMoreElements()) {  @b@						ip = address.nextElement();  @b@						if (ip.isSiteLocalAddress()  @b@								&& !ip.isLoopbackAddress()  @b@								&& ip.getHostAddress().indexOf(":") == -1) {// 内网IP  @b@							return HexStringUtils.encrypt(ni.getHardwareAddress());@b@						}  @b@					}@b@					if (ret != null) {@b@						ret = HexStringUtils.encrypt(ni.getHardwareAddress());@b@					}@b@				}@b@			}  @b@		} catch (Exception e) {@b@		}  @b@		return ret;@b@	}@b@@b@	public static String getIp() {  @b@		String ret = null; // 优先外网@b@		try {  @b@			Enumeration<NetworkInterface> netInterfaces = NetworkInterface  @b@					.getNetworkInterfaces();  @b@			InetAddress ip = null;  @b@			while (netInterfaces.hasMoreElements()) {  @b@				NetworkInterface ni = netInterfaces.nextElement(); @b@				Enumeration<InetAddress> address = ni.getInetAddresses();  @b@				while (address.hasMoreElements()) {  @b@					ip = address.nextElement();  @b@					if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()  @b@							&& ip.getHostAddress().indexOf(":") == -1) {// 外网IP  @b@						return ip.getHostAddress();  @b@					} else if (ip.isSiteLocalAddress()  @b@							&& !ip.isLoopbackAddress()  @b@							&& ip.getHostAddress().indexOf(":") == -1) {// 内网IP  @b@						ret = ip.getHostAddress();  @b@					}  @b@				}  @b@			}  @b@		} catch (Exception e) {@b@		}  @b@		return ret;@b@	}  @b@}