2

i am using NetworkInterface class to get the MAC address but i am getting null in my code NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddr); .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.

Neetesh
  • 917
  • 1
  • 6
  • 16
Ashish Tamrakar
  • 810
  • 10
  • 24

2 Answers2

3

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;
}
}
Neetesh
  • 917
  • 1
  • 6
  • 16
2

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?

Community
  • 1
  • 1
Neetesh
  • 917
  • 1
  • 6
  • 16
  • Thanks a lot sir,but this will return the Ip address of a machine on LAN,will you please tell me ow to get the MAC Address of a machine as i am in need of MAC Address to uniquely identify the machine on LAN....I will be graceful to you for that – Ashish Tamrakar Apr 05 '12 at 09:50