java獲取本機名稱、IP、MAC地址和網卡名稱
摘自:https://blog.csdn.net/Dai_Haijiao/article/details/80364370
2018年05月18日 14:53:19
閱讀數:134
-
import java.net.InetAddress;
-
import java.net.NetworkInterface;
-
-
public
class IpConfig {
-
@SuppressWarnings(
"static-access")
-
public static void main(String[] args) throws Exception {
-
InetAddress ia =
null;
-
try {
-
ia = ia.getLocalHost();
-
String localname = ia.getHostName();
-
String localip = ia.getHostAddress();
-
System.out.println(
"本機名稱是:" + localname);
-
System.out.println(
"本機的ip是 :" + localip);
-
}
catch (Exception e) {
-
e.printStackTrace();
-
}
-
InetAddress ia1 = InetAddress.getLocalHost();
// 獲取本地IP對象
-
System.out.println(
"本機的MAC是 :" + getMACAddress(ia1));
-
}
-
-
// 獲取MAC地址的方法
-
private static String getMACAddress(InetAddress ia) throws Exception {
-
// 獲得網絡接口對象(即網卡),並得到mac地址,mac地址存在於一個byte數組中。
-
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
-
// 下面代碼是把mac地址拼裝成String
-
StringBuffer sb =
new StringBuffer();
-
for (
int i =
0; i < mac.length; i++) {
-
if (i !=
0) {
-
sb.append(
"-");
-
}
-
// mac[i] & 0xFF 是為了把byte轉化為正整數
-
String s = Integer.toHexString(mac[i] &
0xFF);
-
// System.out.println("--------------");
-
// System.err.println(s);
-
sb.append(s.length() ==
1 ?
0 + s : s);
-
}
-
// 把字符串所有小寫字母改為大寫成為正規的mac地址並返回
-
return sb.toString().toUpperCase();
-
}
-
}
輸出結果如下:
本機名稱是:PC-DaiHaijiao
本機的ip是 :172.16.0.31
本機的MAC是 :00-FF-0D-99-5E-1E
-
import java.net.Inet4Address;
-
import java.net.InetAddress;
-
import java.net.NetworkInterface;
-
import java.util.Enumeration;
-
-
public
class NetworkInterfaceTest {
-
-
public static void main(String[] args) throws Exception {
-
// 獲得本機的所有網絡接口
-
Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
-
while (nifs.hasMoreElements()) {
-
NetworkInterface nif = nifs.nextElement();
-
// 獲得與該網絡接口綁定的 IP 地址,一般只有一個
-
Enumeration<InetAddress> addresses = nif.getInetAddresses();
-
while (addresses.hasMoreElements()) {
-
InetAddress addr = addresses.nextElement();
-
if (addr
instanceof Inet4Address) {
// 只關心 IPv4 地址
-
System.out.println(
"網卡接口名稱:" + nif.getName());
-
System.out.println(
"網卡接口地址:" + addr.getHostAddress());
-
System.out.println();
-
}
-
}
-
}
-
}
-
}
輸出結果如下:
網卡接口名稱:lo
網卡接口地址:127.0.0.1
網卡接口名稱:eth0
網卡接口地址:172.16.0.31
網卡接口名稱:eth2
網卡接口地址:192.168.220.1
網卡接口名稱:wlan2
網卡接口地址:192.168.0.108
網卡接口名稱:eth8
網卡接口地址:192.168.138.1