由于 JavaScript 运行在浏览器中,它无法直接访问计算机的 IP 地址和 MAC 地址,因为这些信息是在网络层和物理层上处理的。但是,可以使用一些技术来获取类似的信息。

获取 IP 地址:

可以使用 WebRTC(Web Real-Time Communications)技术来获取浏览器的 IP 地址。WebRTC 是一个支持浏览器之间实时通信的 API 集合,其中包含一个 'RTCPeerConnection' 对象,它可以获取本地 IP 地址。

以下是一个使用 WebRTC 获取 IP 地址的示例代码:

//获取IP地址
function getIPAddress() {
  return new Promise((resolve, reject) => {
    const RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
    if (!RTCPeerConnection) {
      reject('不支持 WebRTC');
      return;
    }
    const pc = new RTCPeerConnection();
    pc.createDataChannel('');
    pc.createOffer((sdp) => {
      pc.setLocalDescription(sdp);
    }, (error) => {
      reject(error);
    });
    pc.onicecandidate = (event) => {
      if (event.candidate) {
        const ipRegex = /([0-9]{1,3}(.[0-9]{1,3}){3})/
        const ipMatch = ipRegex.exec(event.candidate.candidate);
        if (ipMatch) {
          resolve(ipMatch[1]);
        }
      }
    };
  });
}

//使用示例
getIPAddress().then(ip => {
  console.log('IP 地址:' + ip);
}).catch(error => {
  console.error(error);
});

获取 MAC 地址:

在浏览器中,无法直接获取计算机的 MAC 地址。但是,可以使用一些技术来获取本地网络接口的 MAC 地址。

以下是一个使用 WebAPI 获取本地网络接口的 MAC 地址的示例代码:

//获取MAC地址
function getMACAddress() {
  return new Promise((resolve, reject) => {
    const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
    const isWindows = navigator.platform.toUpperCase().indexOf('WIN') >= 0;
    if (!isMac && !isWindows) {
      reject('不支持获取 MAC 地址');
      return;
    }
    const networkInterfaces = window.navigator.networkInterfaces();
    const interfaceNames = Object.keys(networkInterfaces);
    for (let i = 0; i < interfaceNames.length; i++) {
      const interfaceName = interfaceNames[i];
      const interfaceObj = networkInterfaces[interfaceName];
      if (interfaceObj.length > 0) {
        const macAddress = interfaceObj[0].mac;
        if (macAddress) {
          resolve(macAddress);
          return;
        }
      }
    }
    reject('无法获取 MAC 地址');
  });
}

//使用示例
getMACAddress().then(mac => {
  console.log('MAC 地址:' + mac);
}).catch(error => {
  console.error(error);
});

需要注意的是,以上方法仅适用于支持 WebRTC 和 WebAPI 的浏览器。在一些老旧的浏览器中,可能无法获取 IP 地址和 MAC 地址。

JavaScript 获取 IP 地址和 MAC 地址指南

原文地址: https://www.cveoy.top/t/topic/mKrx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录