How to get the viewer's IP address and MAC address using JavaScript

PHPz
Release: 2023-04-24 14:57:19
Original
8864 people have browsed it

With the popularity and development of the Internet, more and more applications need to obtain the IP address and MAC address of visitors. In many cases, we need to use JavaScript to achieve this function.

This article will introduce how to use JavaScript to obtain the visitor's IP address and MAC address and write them into the database.

1. Obtain the visitor's IP address

Obtaining the visitor's IP address in Javascript is mainly obtained by accessing the back-end server. A common method is to send a request to the server and have the server return the browser's IP address. The following is a sample code:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.ipify.org', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      var ip = xhr.responseText;
      console.log(ip);
      // 将ip地址写入数据库
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.send(null);
Copy after login

This code uses XMLHttpRequest to send a GET request to the https://api.ipify.org URL, and obtains the IP address returned by the server after the request is completed.

In actual applications, we may encounter problems with cross-domain requests. If the requested site is different from the domain name of the current page, the browser will prevent XMLHttpRequest from sending the request and return a "Cross-domain access is prohibited" error.

There are two main ways to solve cross-domain problems. One is to use JSONP technology. JSONP is a technical means of cross-domain access. It obtains data by dynamically adding a

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template