久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Java:獲取本機的所有Mac地址

瀏覽:131日期:2024-02-10 13:38:02

問題描述

public class Mac { public static void main(String[] args) {try { Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) {StringBuffer stringBuffer = new StringBuffer();NetworkInterface networkInterface = enumeration.nextElement();if (networkInterface != null) { byte[] bytes = networkInterface.getHardwareAddress(); if (bytes != null) {for (int i = 0; i < bytes.length; i++) { if (i != 0) {stringBuffer.append('-'); } int tmp = bytes[i] & 0xff; // 字節(jié)轉換為整數 String str = Integer.toHexString(tmp); if (str.length() == 1) {stringBuffer.append('0' + str); } else {stringBuffer.append(str); }}String mac = stringBuffer.toString().toUpperCase(); System.out.println(mac); }} }} catch (Exception e) { e.printStackTrace();} }}

在我的開發(fā)機(Windows)上運行上面代碼可以獲取多個Mac地址(安裝了VM有若干虛擬的),但在服務器上卻只能獲取到一個Mac地址,請問這是為什么呢?

Java:獲取本機的所有Mac地址Java:獲取本機的所有Mac地址

我卻只能獲取到【XX-XX-54-B3-6B-28】這一個Mac請問為什么呢?應該一個是有線網卡,一個是無線網卡獲取到兩個才對,可是【XX-XX-54-B3-6B-29】卻獲取不到

===========================分割線============================

仍未找到問題所在,臨時解決辦法是Windows中使用以上代碼獲取所有Mac,而在Linux(CentOS 7.0)中通過讀取

public class Mac { public static void main(String[] args) throws Exception {StringBuffer sb = new StringBuffer();try { String str = 'cat /sys/class/net/*/address | sed -n ’1p’'; String[] cmd = new String[] { '/bin/sh', '-c', str }; Process process = Runtime.getRuntime().exec(cmd); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = br.readLine()) != null) {sb.append(line); }} catch (IOException e) { e.printStackTrace();}String mac = sb.toString().replace(':', '-').toUpperCase(); }}

問題解答

回答1:

你服務器上 eno2 那個網絡接口的 flag 沒有 running 狀態(tài),是不是沒啟用?用 mii-tool 之類的命令檢查一下。

回答2:

InetAddress address = InetAddress.getLocalHost(); NetworkInterface ni = NetworkInterface.getByInetAddress(address); byte[] macs = ni.getHardwareAddress(); String mac = ''; Formatter formatter = new Formatter(); for (int i = 0; i < macs.length; i++) { mac = formatter.format(Locale.getDefault(), '%02X%s', macs[i], i < macs.length - 1 ? '-' : '').toString(); } return mac; 回答3:

你服務器上還裝了無線網卡? 我臺式機都沒裝

標簽: java
相關文章:
主站蜘蛛池模板: 高阳县| 河间市| 汽车| 玉屏| 明光市| 衡阳市| 华坪县| 剑阁县| 罗甸县| 宁都县| 会东县| 黎川县| 志丹县| 湘潭市| 庆城县| 南丰县| 内江市| 哈巴河县| 永仁县| 锡林浩特市| 涿州市| 夏邑县| 安塞县| 盈江县| 永昌县| 尼勒克县| 乡宁县| 徐汇区| 平顺县| 东阳市| 新绛县| 通化市| 原平市| 陵水| 福泉市| 葫芦岛市| 武邑县| 南木林县| 恩施市| 永和县| 武汉市|