Last active
December 30, 2015 21:19
-
-
Save gogomarine/7886777 to your computer and use it in GitHub Desktop.
工具类,获取当前机器物理网卡信息,包括IP、Mac地址等
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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