JavaScript 如何获取客户端IP地址

JavaScript 如何获取客户端IP地址

在本文中,我们将了解如何在JavaScript中获取客户端的IP地址。IP地址是一组数字,用于唯一标识某个系统。它就像一个有地址用来接收邮件的房子一样。类似地,你的计算机有一个地址用来接收来自网络的数据。”协议”一词指的是在浏览全球连接时需要遵循的一些指南。互联网的网络部分由确切的规范(指南)定义。

为了获取客户端的公共IP地址,JavaScript作为第三方服务器端语言。JavaScript无法独自完成,因此添加了jQuery来实现此功能。JavaScript与第三方应用程序配合使用来获取IP地址。这些是获取用户IP地址并以纯文本、JSON和JSONP格式返回IP地址的应用程序服务。互联网上有很多这样的服务可用。在这里,我们将使用ipify和ipinfo两个最常用的工具来查找IP地址。

示例1: 在这个示例中,我们将使用ipify来获取具有SSL內容的网站(使用https协议)的客户端IP地址。

<!DOCTYPE html>
<html>
 
<head>
    <title>Getting Clients IP</title>
    <style>
    p, h1 {
        color: green;
    }
    </style>
  
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
     
      <script>
     
    /* Add "https://api.ipify.org?format=json" statement
               this will communicate with the ipify servers in
               order to retrieve the IP address .getJSON will
               load JSON-encoded data from the server using a
               GET HTTP request */
                
    .getJSON("https://api.ipify.org?format=json", function(data) {
         
        // Setting text of element P with id gfg
        $("#gfg").html(data.ip);
    })
    </script>
</head>
 
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <h3>Public IP Address of user is:</h3>
        <p id="gfg"></p>
 
    </center>
</body>
 
</html>
HTML

输出:

JavaScript 如何获取客户端IP地址

示例2: 在此示例中,我们将使用 ipinfo 来获取客户端的IP地址,并在提示框中显示。

<!DOCTYPE html>
<html>
 
<head>
    <title>Getting Clients IP</title>
     
    <style>
    h1 {
        color: green;
    }
    </style>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
     
    <script>
     
    // Add "https://ipinfo.io" statement
    // this will communicate with the ipify servers 
    // in order to retrieve the IP address
    $.get("https://ipinfo.io", function(response) {
            alert(response.ip);
        }, "json")
         
        // "json" shows that data will be fetched in json format
    </script>
</head>
 
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <h3>Getting Client IP address</h3>
    </center>
</body>
 
</html>
HTML

输出:

JavaScript 如何获取客户端IP地址

注意: 有时在默认设置下,它在Google Chrome和Internet Explorer上无法正常工作。它支持Firefox和Microsoft Edge。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册