Skip to content

Instantly share code, notes, and snippets.

@gogomarine
Last active December 30, 2015 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gogomarine/7886777 to your computer and use it in GitHub Desktop.
Save gogomarine/7886777 to your computer and use it in GitHub Desktop.
工具类,获取当前机器物理网卡信息,包括IP、Mac地址等
public class Utils {
//ipv4的判断规则
private static final Pattern IPV4 = Pattern.compile("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}");
/**
* 这个过滤了 是回路的地址
*
* */
public static List<String> getIpAddresses() {
Set<String> ipAddresses= new HashSet();
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface ifc = enumeration.nextElement();
if (ifc != null && ifc.isUp()) {
Enumeration<InetAddress> addresses = ifc.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address != null && !address.isLoopbackAddress() && isIpv4(address.getHostAddress())) {
ipAddresses.add(address.getHostAddress());
}
}
}
}
} catch (SocketException e) {
logger.error("无法获取本地网卡信息" + e.getMessage());
}
return new ArrayList(ipAddresses);
}
public static boolean isIpv4(String ip) {
return IPV4.matcher(ip).matches();
}
public static List<String> getMacAddresses() {
Set<String> macAddresses = Sets.newHashSet();
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface ifc = enumeration.nextElement();
if (ifc != null && ifc.isUp()) {
byte[] macBytes = ifc.getHardwareAddress();
if (macBytes != null) {
String mac = new String(Hex.encodeHex(macBytes));
if (StringUtils.length(mac) == 12) {
macAddresses.add(mac);
}
}
}
}
} catch (SocketException e) {
logger.error("无法获取本地MAC信息" + e.getMessage());
}
return Lists.newArrayList(macAddresses);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment