search
HomeWeb Front-endFront-end Q&AHow to get the viewer's IP address and MAC address using JavaScript

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);

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 <script> tag. The other is to use CORS technology. CORS is the English abbreviation of cross-origin resource sharing, which allows resources to be accessed across specified domains on the requested server. </script>

2. Obtaining the visitor’s MAC address

Obtaining the visitor’s MAC address in JavaScript is more complicated than obtaining the IP address. Because obtaining the MAC address requires the use of Java or Flash plug-ins provided by the browser, they need to be authorized by the user to run.

Here, we introduce a method to obtain the MAC address based on Java Applet. Java Applet is a special type in Java that can run in a web browser and has certain system permissions.

First, create a Java Applet program on the server to obtain the MAC address. The following is a sample code:

import java.applet.Applet;
import java.applet.AppletContext;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class MACAddress extends Applet {
  public void start() {
    try {
      Enumeration<networkinterface> interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface ni = interfaces.nextElement();
        byte[] hardwareAddress = ni.getHardwareAddress();
        if (hardwareAddress != null) {
          StringBuilder macAddress = new StringBuilder("");
          for (byte b : hardwareAddress) {
            macAddress.append(String.format("%02X", b));
          }
          String mac = macAddress.toString();
          System.out.println(mac);
          // 将mac地址写入数据库
          break;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}</networkinterface>

In this code, we use the NetworkInterface class provided by Java to obtain the MAC address of the network card, and then convert the MAC address into a hexadecimal string and output it to the console . In practical applications, we can modify this code to write the MAC address into the database.

Then, add the Applet embedding code to the HTML page:

<object>
  <param>
  <param>
  <param>
  <param>
  <embed>
  </embed>
</object>

In this code, we use the and tags to embed the Java Applet. Among them, classid is the name and location of the specified Java class, codebase is the storage location of the specified Applet, and archive is the archive file of the specified Applet. Then, we can add this code to the appropriate location on the page.

3. Write to the database

After obtaining the browser’s IP address and MAC address, we need to write them to the database. Here we can achieve it with the help of Ajax technology.

The following is a sample code for writing an IP address:

var xhr = new XMLHttpRequest();
xhr.open('POST', '/writeip.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log('IP地址写入成功');
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.send('ip=' + encodeURIComponent(ip));

In this code, we use XMLHttpRequest to send a POST request to the /writeip.php backend interface, and when the request is completed Then output the result.

We need to write a writeip.php file on the backend to process interface requests and write the IP address to the database. The following is a sample code:

<?php $ip = $_POST[&#39;ip&#39;];

// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 插入数据
$stmt = $conn->prepare("INSERT INTO ip_info (ip) VALUES (?)");
$stmt->bind_param("s", $ip);
$stmt->execute();
$stmt->close();

$conn->close();
?>

This code uses mysqli to connect to the database and insert the IP address into the ip_info table.

The method of writing the MAC address is similar and will not be repeated here.

Summary

This article describes how to use JavaScript to obtain the viewer's IP address and MAC address and write them into the database. The method of obtaining the IP address is to send a request to the server and let the server return the browser's IP address; the method of obtaining the MAC address is to use the Java Applet program and embed the Java Applet code in the HTML page. We can then write them to the database using Ajax technology. In actual applications, we need to test and handle different browsers and operating systems to ensure the compatibility and reliability of the code.

The above is the detailed content of How to get the viewer's IP address and MAC address using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function