Get MAC Address with java


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

3 Responses

  1. Just passing by.Btw, you website have great content!

    ______________________________
    Don’t pay for your electricity any longer…
    Instead, the power company will pay YOU!

  2. You can get all all mac address by using:

    public static List macAddress() {
    try {
    InetAddress[] addresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
    List listMac = new ArrayList();

    /*
    * Get NetworkInterface for the current host and then read the
    * hardware address.
    */
    NetworkInterface ni = null;
    byte[] mac = null;
    StringBuffer strBuf = null;
    for (InetAddress address : addresses) {
    ni = NetworkInterface.getByInetAddress(address);
    mac = ni.getHardwareAddress();

    /*
    * Extract each array of mac address and convert it to hexa with the
    * following format 08-00-27-DC-4A-9E.
    */
    strBuf = new StringBuffer();
    for (int i = 0; i < mac.length; i++) {
    strBuf.append(String.format(“%02X%s”, mac[i], (i < mac.length – 1) ? “-” : “”));
    }
    listMac.add(strBuf.toString());
    }
    return listMac;
    } catch (Exception e) {
    }
    return null;
    }

  3. Thanks alot. This was just what I was Looking for.!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: