Java获取Mac地址及IP地址2014-12-24 03:28:51
( 1人已投票,[高质量] )
源生Java获取Mac地址及IP地址的代码:
测试环境:windows linux unix
[注]:请勿用localhost 127.0.0.1测试
Java代码如下:
IpUtil.java
import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class IpUtil { private IpUtil(){} public static String getLocalIP() { //get local Ip address String sIP = ""; InetAddress ip = null; try { boolean bFindIP = false; Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface .getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { if (bFindIP) { break; } NetworkInterface ni = (NetworkInterface) netInterfaces .nextElement(); Enumeration<InetAddress> ips = ni.getInetAddresses(); while (ips.hasMoreElements()) { ip = (InetAddress) ips.nextElement(); if (!ip.isLoopbackAddress() && ip.getHostAddress().matches( "(\\d{1,3}\\.){3}\\d{1,3}")) { bFindIP = true; break; } } } } catch (Exception e) { e.printStackTrace(); } if (null != ip) { sIP = ip.getHostAddress(); } return sIP; } public static String getMacId() { //get Mac address String macId = ""; InetAddress ip = null; NetworkInterface ni = null; try { boolean bFindIP = false; Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface .getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { if (bFindIP) { break; } ni = (NetworkInterface) netInterfaces .nextElement(); // ni.getName // 遍历IP Enumeration<InetAddress> ips = ni.getInetAddresses(); while (ips.hasMoreElements()) { ip = (InetAddress) ips.nextElement(); if (!ip.isLoopbackAddress() // 不是127.0.0.1 && ip.getHostAddress().matches( "(\\d{1,3}\\.){3}\\d{1,3}")) { bFindIP = true; break; } } } } catch (Exception e) { e.printStackTrace(); } if (null != ip) { try { macId = getMacFromBytes(ni.getHardwareAddress()); } catch (SocketException e) { e.printStackTrace(); } } return macId; } private static String getMacFromBytes(byte[] bytes) { StringBuffer mac = new StringBuffer(); byte currentByte; boolean first = false; for (byte b : bytes) { if (first) { mac.append("-"); } currentByte = (byte) ((b & 240) >> 4); mac.append(Integer.toHexString(currentByte)); currentByte = (byte) (b & 15); mac.append(Integer.toHexString(currentByte)); first = true; } return mac.toString().toUpperCase(); } public static void main(String[] args) throws SocketException { System.out.println(getLocalIP()); System.out.println(getMacId()); } }
上一篇:最最让十二星座难以忍受的爱情
下一篇:Eclipse安装Git方案大全