Get MAC address on local machine with Java

2019-01-03 00:02发布

I can use

ip = InetAddress.getLocalHost();
NetworkInterface.getByInetAddress(ip);

to obtain the mac address, but if I use this code in an offline machine it doesn't work.

So, How can I get the Mac address?

8条回答
手持菜刀,她持情操
2楼-- · 2019-01-03 00:15

Try this:

final NetworkInterface netInf = NetworkInterface.getNetworkInterfaces().nextElement();
final byte[] mac = netInf.getHardwareAddress();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
}
log.info("Mac addr: {}", sb.toString());
查看更多
我命由我不由天
3楼-- · 2019-01-03 00:17
public static void main(String[] args){

        InetAddress ip;
        try {

            ip = InetAddress.getLocalHost();
            System.out.println("Current IP address : " + ip.getHostAddress());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);

            byte[] mac = network.getHardwareAddress();

            System.out.print("Current MAC address : ");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            System.out.println(sb.toString());

        } catch (Exception e) {

            e.printStackTrace();

        }

       }

output:

Current IP address : 192.168.21.60
Current MAC address : 70-5A-0F-3C-84-F2
查看更多
唯我独甜
4楼-- · 2019-01-03 00:20

@Jesus Flores, still not working for me, this code:

element.getHardwareAddress().length > 0 

is throwing exception. We have to check for null. Final solution in your case that is working for me:

            while (addresses.hasMoreElements()
                    && element.getHardwareAddress() != null
                    && element.getHardwareAddress().length > 0
                    && !isVMMac(element.getHardwareAddress())) {
                final InetAddress ip = addresses.nextElement();
                if (ip instanceof Inet4Address) {
                    // || ip instanceof Inet6Address
                    if (ip.isSiteLocalAddress()) {
                        ipAddress = ip.getHostAddress();
                        lanIp = InetAddress.getByName(ipAddress);
                    }
                }
            }

I am working always over wi-fi.

查看更多
Deceive 欺骗
5楼-- · 2019-01-03 00:21

Another way is to use an OS command 'getmac' through native code execution.

    Process p = Runtime.getRuntime().exec("getmac /fo csv /nh");
    java.io.BufferedReader in = new java.io.BufferedReader(new  java.io.InputStreamReader(p.getInputStream()));
    String line;
    line = in.readLine();        
    String[] result = line.split(",");

    System.out.println(result[0].replace('"', ' ').trim());
查看更多
放荡不羁爱自由
6楼-- · 2019-01-03 00:24

Cleaned up code from here:

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class HardwareAddress
{
    public static String getMacAddress() throws UnknownHostException,
            SocketException
    {
        InetAddress ipAddress = InetAddress.getLocalHost();
        NetworkInterface networkInterface = NetworkInterface
                .getByInetAddress(ipAddress);
        byte[] macAddressBytes = networkInterface.getHardwareAddress();
        StringBuilder macAddressBuilder = new StringBuilder();

        for (int macAddressByteIndex = 0; macAddressByteIndex < macAddressBytes.length; macAddressByteIndex++)
        {
            String macAddressHexByte = String.format("%02X",
                    macAddressBytes[macAddressByteIndex]);
            macAddressBuilder.append(macAddressHexByte);

            if (macAddressByteIndex != macAddressBytes.length - 1)
            {
                macAddressBuilder.append(":");
            }
        }

        return macAddressBuilder.toString();
    }
}
查看更多
Luminary・发光体
7楼-- · 2019-01-03 00:25

With all the possible solutions that i've found here and another replies, then i will contribute with my solution. You need to specify a parameter with a String containing "ip" or "mac" depending on what you need to check. If the computer has no interface, then it will return an String containing null, otherwise will return a String containing what you asked for (the ip address or the mac).

How to use it:

System.out.println("Ip: " + GetNetworkAddress.GetAddress("ip"));
System.out.println("Mac: " + GetNetworkAddress.GetAddress("mac"));

Result (if the computer has a network card):

Ip: 192.168.0.10 
Mac: 0D-73-ED-0A-27-44

Result (if the computer doesn't have a network card):

Ip: null
Mac: null

Here's the code:

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class GetNetworkAddress {

    public static String GetAddress(String addressType) {
        String address = "";
        InetAddress lanIp = null;
        try {

            String ipAddress = null;
            Enumeration<NetworkInterface> net = null;
            net = NetworkInterface.getNetworkInterfaces();

            while (net.hasMoreElements()) {
                NetworkInterface element = net.nextElement();
                Enumeration<InetAddress> addresses = element.getInetAddresses();

                while (addresses.hasMoreElements() && element.getHardwareAddress().length > 0 && !isVMMac(element.getHardwareAddress())) {
                    InetAddress ip = addresses.nextElement();
                    if (ip instanceof Inet4Address) {

                        if (ip.isSiteLocalAddress()) {
                            ipAddress = ip.getHostAddress();
                            lanIp = InetAddress.getByName(ipAddress);
                        }

                    }

                }
            }

            if (lanIp == null)
                return null;

            if (addressType.equals("ip")) {

                address = lanIp.toString().replaceAll("^/+", "");

            } else if (addressType.equals("mac")) {

                address = getMacAddress(lanIp);

            } else {

                throw new Exception("Specify \"ip\" or \"mac\"");

            }

        } catch (UnknownHostException ex) {

            ex.printStackTrace();

        } catch (SocketException ex) {

            ex.printStackTrace();

        } catch (Exception ex) {

            ex.printStackTrace();

        }

        return address;

    }

    private static String getMacAddress(InetAddress ip) {
        String address = null;
        try {

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            byte[] mac = network.getHardwareAddress();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            address = sb.toString();

        } catch (SocketException ex) {

            ex.printStackTrace();

        }

        return address;
    }

    private static boolean isVMMac(byte[] mac) {
        if(null == mac) return false;
        byte invalidMacs[][] = {
                {0x00, 0x05, 0x69},             //VMWare
                {0x00, 0x1C, 0x14},             //VMWare
                {0x00, 0x0C, 0x29},             //VMWare
                {0x00, 0x50, 0x56},             //VMWare
                {0x08, 0x00, 0x27},             //Virtualbox
                {0x0A, 0x00, 0x27},             //Virtualbox
                {0x00, 0x03, (byte)0xFF},       //Virtual-PC
                {0x00, 0x15, 0x5D}              //Hyper-V
        };

        for (byte[] invalid: invalidMacs){
            if (invalid[0] == mac[0] && invalid[1] == mac[1] && invalid[2] == mac[2]) return true;
        }

        return false;
    }

}

UPDATED 02/05/2017: Thanks to @mateuscb on the post How to Determine Internet Network Interface in Java that unfortunately didn't get any upvote on that post before, but he contributed to this update.

The method has been improved to skip virtual machine network cards (most popular VM software)

查看更多
登录 后发表回答