public class IpAddressUtils {
private static final String INTRANET_IP = getLocalIpAddress();
public static String getLocalMacAddress(String ip) {//没有缓存的地址,则查询
String mac_s = "";
try {
byte[] mac;
NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(ip));
mac = ne.getHardwareAddress();
mac_s = byte2hex(mac);
} catch (Exception e) {
}
return mac_s;
}
private static String byte2hex(byte[] mac) {
StringBuilder sb = new StringBuilder();;
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
String string = sb.toString();
return string;
}
/**
* 获取本地IP
*
* @return
*/
public static String getLocalIpAddress() {
try{
return InetAddress.getLocalHost().getHostAddress();
} catch(Exception e){
throw new RuntimeException(e);
}
}
/**
* 获得外网IP
* @return 外网IP
*/
public static String getInternetIp(){
try{
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
Enumeration<InetAddress> addrs;
while (networks.hasMoreElements())
{
addrs = networks.nextElement().getInetAddresses();
while (addrs.hasMoreElements())
{
ip = addrs.nextElement();
if (ip != null
&& ip instanceof Inet4Address
&& ip.isSiteLocalAddress()
&& !ip.getHostAddress().equals(INTRANET_IP))
{
return ip.getHostAddress();
}
}
}
// 如果没有外网IP,就返回内网IP
return INTRANET_IP;
} catch(Exception e){
throw new RuntimeException(e);
}
}
}
java获取MAC地址
最新推荐文章于 2024-04-03 08:00:00 发布