【问题标题】:Check local (internal) IP with JavaScript使用 JavaScript 检查本地(内部)IP
【发布时间】:2015-09-12 15:51:00
【问题描述】:

我知道这看起来像是重复的,但老实说,我无法找到任何解决此问题的答案。

我在只能访问 www.example.com 的网络上使用静态 IP 地址设置了两台 iPad(网络限制,而不是 iPad 限制)。 example.com 是一个电子商务网站,我想在这两个 iPad 中的任何一个访问该网站时填写优惠券字段。

我能想到的唯一方法是获取 iPad 的本地 IP 地址(例如 192.168.0.x)并创建一个白名单数组。但我的问题是尝试检测浏览设备的本地 IP。

我无法使用 example.com 域之外的任何资源,也无法使用网络的公共 IP,因为将连接许多其他设备。

另外,我尝试过 WebRTC,但它只有 Chrome 和 Firefox,而且我仅限于 iPad 的原生 Safari 浏览器。

帮我溢出克诺比,你是我唯一的希望!

编辑

情况发生了变化。我发现没有其他设备会使用结帐服务,所以我现在可以定位外部 IP。下面是我如何做到这一点的详细信息。

【问题讨论】:

  • java 和 rtc 是我见过的从 JS 获取 IP 的唯一 hack,它们本身并不能提供这种能力。
  • 我对任何选项持开放态度,即使有一个 PHP 替代方案我可以转入 JS。虽然我对 PHP 的经验很少。

标签: javascript ip


【解决方案1】:

好的,我找到了解决问题的方法。

首先更正我原来的问题:

我刚刚发现网络上的其他设备实际上都不会用于在网站上进行购买,因此 iPad 是仅有的两个将进入结帐的设备。

现在知道了这一点,我可以定位网络的公共 IP。我使用两个脚本完成了这项工作,一个在外部 PHP 文件中(我们的服务器未设置为在 HTML 文件中运行 PHP),另一个在外部 JavaScript 文件中(更易于管理,因为结帐页面有多个版本,所以如果我需要更改折扣代码,我只需更新 JS 文件。)

PHP 文件:

// Declare content as JavaScript
Header("content-type: application/x-javascript");
// Declare variables for IP adress requests
$http_client_ip = $_SERVER['HTTP_CLIENT_IP'];
$http_x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'];
$remote_addr = $_SERVER['REMOTE_ADDR'];

// Request for most accurate IP address
if (!empty($http_client_ip)) {
    $ip_address = $http_client_ip;
} else if (!empty($http_x_forwarded_for)) {
    $ip_address = $http_x_forwarded_for;
} else {
    $ip_address = $remote_addr;
}

// Add results to array - multiple IP addresses may be returned
$list = explode(',', $ip_address, 2);

// Write the first IP address in array as JavaScript
echo 'document.write(\'<div class="myIP" style="display:none;">' . $list[0] . '</div>\')';

JS 文件:

// Array of allowed IP addresses
var allowedIP = ['x.x.x.x'];
// Coupon code
var couponCode = "CODE001";

// Run script when page is loaded
$(document).ready(function () {
    // Get device IP from 'myIP' div loaded by php
    var ipAddress = $('.myIP').text();
    // Check if device IP matches any of the IPs in the Allowed array
    for (var i = 0; i<allowedIP.length;i++) {
        if (ipAddress == allowedIP[i]) {
            // If it matches, write to console
            console.log("Your external IP is allowed");
            // Add coupon code to input field
            $('input[name="coupon"]').val(couponCode);
        } else {
            // If it does not match, write to console
            console.log("Sorry buddy, you're not on the list.");
        }
    };
});

【讨论】:

    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 2013-08-22
    • 2017-05-21
    • 2012-08-03
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多