91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
邵武市| 郁南县| 邵东县| 涪陵区| 台东市| 天等县| 万安县| 芦溪县| 合水县| 吉林省| 四会市| 白水县| 新营市| 东城区| 农安县| 涿鹿县| 葫芦岛市| 大关县| 英超| 斗六市| 尼玛县| 忻城县| 汉川市| 桃源县| 彰武县| 阳高县| 库尔勒市| 北海市| 镇平县| 陈巴尔虎旗| 北辰区| 舞阳县| 富蕴县| 涟水县| 嘉义县| 穆棱市| 涪陵区| 都兰县| 屏东县| 宣武区| 呼玛县|