1

I need to get MAC address in my nativescript/typescript project on Android platform. I haven't found any plugin to do this so i think the only way is to use native API. Can you provide me the code in typescript to do this? Thanks

  • Use this https://stackoverflow.com/a/10831640/4936697 but of course, you need to convert the Java code to TypeScript (look for documentation about the marshaling in NativeScript) – Nick Iliev Jan 30 '20 at 11:38
  • This talks about Android 6, I need for Android 8.1.0 :/ The code for 8.1.0 is more difficult to translate – Marco Zanaboni Jan 30 '20 at 12:06
  • Ouch you are right.. it returns a constant dummy value instead of the real MAC – Nick Iliev Jan 30 '20 at 12:40

1 Answers1

1

Try this (tested on Android 10)

try {
    const collection = java.util.Collections.list(java.net.NetworkInterface.getNetworkInterfaces());
    const iterator = collection.iterator();

    while (iterator.hasNext()) {
      const nif = iterator.next(),
        name = nif.getName();

      if (name !== "wlan0") {
        continue;
      }

      const macBytes = nif.getHardwareAddress();
      if (macBytes !== null) {

        const res = new java.lang.StringBuilder();
        for (let i = 0; i < macBytes.length; i++) {
          const b = macBytes[i];
          const hex = java.lang.Integer.toHexString(b & 0xFF);
          if (hex.length == 1) { hex = "0" + hex; }
          res.append(hex + ":");
        }

        if (res.length > 0) {
          res.deleteCharAt(res.length - 1);
        }

        console.log("Mac address: " + res);
      }
    }
  } catch (err) {
    console.log(err)
  }
Manoj
  • 21,753
  • 3
  • 20
  • 41