由于项目上的原因,需要获取本地IP与网络Ip及Mac地址,弄了好半天,才明白过程,于是给大家分享一下。
不说了,直接上代码。
public class GetIpAndMacAddress {
/**
* 获取本机IP
* @throws UnknownHostException
*/
public static String getLocalHostIP() throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
String ip=addr.getHostAddress().toString();//获得本机IP
String address=addr.getHostName().toString();//获得本机名称
return address+":"+ip;
}
/**
* 获取链接网络时分配的IP
* @throws SocketException
*/
public static String getIntentIp() throws SocketException{
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress inetAddress;
String ip = null;
while (networkInterfaces.hasMoreElements()) {
Enumeration<InetAddress> inetAddresses = networkInterfaces.nextElement().getInetAddresses();
while (inetAddresses.hasMoreElements()) {
inetAddress = inetAddresses.nextElement();
if (inetAddress.isSiteLocalAddress() &&inetAddress != null && inetAddress instanceof Inet4Address) {
ip = inetAddress.getHostAddress();
break;
}
}
}
return ip;
}
/**
* 根据网络Ip地址获取Mac地址
* @param host
* @return
* @throws UnknownHostException
* @throws SocketException
*/
public static String getMacAddress(String host) throws IOException {
String macStr = "";
StringBuffer sb = new StringBuffer();
NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(host));
byte[] macs = ni.getHardwareAddress();
for (int i = 0; i < macs.length; i++) {
macStr = Integer.toHexString(macs[i] & 0xFF);
if (macStr.length() == 1) {
macStr = '0' + macStr;
}
sb.append(macStr + "-");
}
macStr = sb.toString();
macStr = macStr.substring(0, macStr.length() - 1);
return macStr;
}
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("IP--:"+GetIpAndMacAddress.getIntentIp());
System.out.println("Mac--:"+GetIpAndMacAddress.getMacAddress(getIntentIp()));
}
}