Home > Mobile >  How to get a MAC address through MATLAB?
How to get a MAC address through MATLAB?

Time:08-24

I am going to design a firewall using MATLAB and I need to get Ethernet data like IP, Port and MAC address to write my filter rules.

How do I obtain those?

CodePudding user response:

The MathWorks Staff has answered this on MATLAB answers:

In order to get MAC information, you can use the Windows command line command 'getmac', and use MATLAB function 'dos' to execute DOS command in MATLAB. The link below describes this function.

web([docroot '/techdoc/ref/dos.html'])

Using the output of this command, you can parse the resulting string output to get MAC address. For instance:

[status,result] = dos('getmac');
mac = result(160:176);

CodePudding user response:

Since you originally had the tag on your question (before the question was edited), here is a more general solution with error checking that should work on Windows, macOS, and on other UNIX/Linux systems:

if ispc
    [status,result] = dos('getmac');
    if status == 0
        mac = result(160:176);
    else
        error('Unable to obtain MAC address.\n%s',result)
    end
elseif isunix
    [status,result] = system('ifconfig en0 | awk ''/ether/ {print $2}''');
    if status == 0
        mac = result(1:end-1); %remove trailing carriage return
    else
        error('Unable to obtain MAC address.\n%s',result);
    end
else
    error('Platform not recognized. Unable to obtain MAC address.');
end

For UNIX-based systems (including macOS), the system function is used to call the ifconfig and awk commands in the terminal.

Note that for both Windows and UNIX this solution returns the MAC address for the primary Ethernet interface on en0. It's possible that on some systems one may need to change this to en1 or another interface ID depending on what ifconfig returns. You can use ifconfig via system to also obtain IP addresses, port number, etc. on UNIX systems.

  • Related