Android: How to get MAC address of Ethernet port (not WiFi)

There are some android devices that have an ethernet (LAN) port for example Android STB, Android powered door-phone monitors, etc. The regular way of getting MAC address is as follows

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();

Not to forget adding the following permission in the AndroidManifest.xml 

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

The above method will give us the MAC address of WiFi. Assuming your Ethernet interface is eth0, to get the MAC address of Ethernet port we have to try opening and reading the file /sys/class/net/eth0/address. This can be Implemented as below.

public static String loadFileAsString(String filePath) throws java.io.IOException{
    StringBuffer data = new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    char[] buf = new char[1024];
    int numRead=0;
    while((numRead=reader.read(buf)) != -1){
        String readData = String.valueOf(buf, 0, numRead);
        data.append(readData);
    }
    reader.close();
    return data.toString();
}

public String getMacAddress(){
    try {
        return loadFileAsString("/sys/class/net/eth0/address")
                .toUpperCase().substring(0, 17);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Dost Muhammad Shah

Dost Muhammad Shah

Dost Muhammad specializing in Embedded Design, Firmware development, PCB designing , testing and prototyping. He enjoys sharing his experience with others .Get in touch with Dost on Twitter or via Contact form

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.