中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

java獲取mac地址的方法有哪些

小億
386
2023-09-05 14:02:44
欄目: 編程語言

在Java中,可以使用以下方法之一來獲取MAC地址:

  1. 使用NetworkInterface類:
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MacAddressUtil {
public static String getMacAddress() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
byte[] mac = networkInterface.getHardwareAddress();
if (mac != null) {
StringBuilder stringBuilder = new StringBuilder();
for (byte b : mac) {
stringBuilder.append(String.format("%02X:", b));
}
if (stringBuilder.length() > 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
return stringBuilder.toString();
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String macAddress = getMacAddress();
System.out.println(macAddress);
}
}
  1. 使用InetAddress類獲取本地主機的IP地址,然后使用Process類執行arp -a命令,解析命令輸出來獲取MAC地址:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MacAddressUtil {
public static String getMacAddress() {
String ipAddress = null;
try {
InetAddress inetAddress = InetAddress.getLocalHost();
ipAddress = inetAddress.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (ipAddress != null) {
try {
Process process = Runtime.getRuntime().exec("arp -a");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(ipAddress)) {
int index = line.indexOf("at") + 3;
return line.substring(index);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
String macAddress = getMacAddress();
System.out.println(macAddress);
}
}

請注意,獲取MAC地址可能因操作系統和網絡環境而異。

0
故城县| 绵阳市| 靖宇县| 兴安县| 禄丰县| 察隅县| 上饶市| 宝山区| 丹凤县| 托克逊县| 鄂托克前旗| 桂林市| 武安市| 台南县| 社会| 颍上县| 紫金县| 全州县| 故城县| 枣阳市| 平邑县| 潜江市| 巫山县| 庆阳市| 汶川县| 都匀市| 卫辉市| 庆安县| 军事| 资中县| 闽清县| 海淀区| 玉树县| 纳雍县| 开封县| 尚义县| 九龙城区| 保定市| 故城县| 收藏| 晋城|