简体   繁体   中英

How to get the MAC address of machine on local network in java

i am using NetworkInterface class to get the MAC address but i am getting null in my code NetworkInterface ni = NetworkInterface.getBy.netAddress(.netAddr); .I am getting null in ni object,pleas suggest me the way to get the mac address of a device on lan.

Thanks in advance.

Try this code,

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;
}
}

Use following lines for getting the host

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

Ashish use this java code and let me know if found any luck. Also check this link if helpful, How to obtain MAC address of WiFi.network interface?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM