2012-04-05 67 views
2

我正在使用NetworkInterface類來獲取MAC地址,但我在我的代碼中爲空NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddr); 。我在ni對象中得到空值,請求建議我以lan的方式獲取設備的mac地址。如何獲得本地網絡上的機器的MAC地址在java

在此先感謝。用於獲取主機

InetAddress address = socket.getInetAddress(); 
String hostIP = addresss.getHostAddress(); 

阿希什

回答

3

試試這個代碼,

import java.io.*; 
import java.net.*; 
import java.util.*; 
import java.util.regex.*; 

public class GetMac 
{ 
public static void main(String[] args) 
throws IOException 
{ 
String address = new GetMac().getMacAddress(); 
System.out.println(address); 
} 

public String getMacAddress() throws IOException 
{ 
String macAddress = null; 
String command = "ipconfig /all"; 
Process pid = Runtime.getRuntime().exec(command); 
BufferedReader in = 
new BufferedReader(
new InputStreamReader(pid.getInputStream())); 
while (true) { 
String line = in.readLine(); 
if (line == null) 
break; 
Pattern p = Pattern.compile(".*Physical Address.*: (.*)"); 
Matcher m = p.matcher(line); 
if (m.matches()) { 
macAddress = m.group(1); 
break; 
} 
} 
in.close(); 
return macAddress; 
} 
} 
+0

非常感謝代碼Neetesh先生,我真的對我很有幫助.. 。 – 2012-04-05 10:05:49

2

使用下面幾行使用Java代碼,讓我知道,如果發現有任何運氣。還要檢查這個鏈接,如果有幫助, How to obtain MAC address of WiFi network interface?

+0

非常感謝先生,但是這將返回局域網的機器的IP地址,請你告訴我嗷嗷得到一臺機器的MAC地址,因爲我需要MAC地址來唯一標識局域網上的機器....我會優雅地對你說這個 – 2012-04-05 09:50:26

相關問題