MAC addresses in JavaScript

MAC Addresses in JavaScript

MAC (Media Access Control) address is a unique identifier assigned to a network interface controller (NIC) for use as a network address in communications within a network segment. In JavaScript, we can retrieve the MAC address of a device using a few different methods.

Method 1: Using the WebRTC API

The WebRTC (Web Real-Time Communication) API provides functions for accessing the local media devices connected to the computer, including the MAC address. Here's how you can retrieve the MAC address using the WebRTC API:


let pc = new RTCPeerConnection();
pc.createDataChannel("");
pc.createOffer(function(offer) {
  let macRegex = /(?:[a-z0-9]{2}:){5}[a-z0-9]{2}/i;
  let macAddress = offer.sdp.match(macRegex)[0];
  console.log(macAddress);
}, function(err) {});
  • Create a new RTCPeerConnection object.
  • Create a new data channel to trigger the generation of an SDP offer.
  • Create an SDP offer using createOffer() method.
  • Parse the MAC address from the offer using a regular expression.

Method 2: Using the Network Information API

The Network Information API provides information about the network connection of the device, including the MAC address. Here's how you can retrieve the MAC address using the Network Information API:


if ('connection' in navigator) {
  let macAddress = navigator.connection.macAddress;
  console.log(macAddress);
} else {
  console.log("Network Information API not supported.");
}
  • Check if the Network Information API is supported by the browser.
  • Retrieve the MAC address using the macAddress property of the connection object.

Method 3: Using a Third-Party Library

There are several third-party libraries available that can retrieve the MAC address of a device using various methods. One of the popular libraries is fingerprintjs2. Here's how you can retrieve the MAC address using fingerprintjs2:


new Fingerprint2().get(function(result, components) {
  let macAddress = components.find(c => c.key === "macAddress").value;
  console.log(macAddress);
});
  • Create a new instance of Fingerprint2 object.
  • Retrieve the MAC address from the components array using the key "macAddress".

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe