使用JavaScript检查本地(内部)IP

时间:2015-06-25 20:49:00

标签: javascript ip

我知道这似乎是重复的,但老实说,我找不到任何可以解决这个问题的答案。

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

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

我不能使用example.com域以外的任何资源,因为会有很多其他设备连接,所以我无法使用网络的公共IP。

另外,我尝试过WebRTC,但它只是Chrome和Firefox,我只能使用iPad的原生Safari浏览器。

帮助我Overflow Kenobi,你是我唯一的希望!

修改

条件已经改变。我发现没有其他设备会使用结账服务,所以我现在可以定位外部IP。有关我如何做到这一点的详细信息如下。

1 个答案:

答案 0 :(得分:0)

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

首先对我原来的问题进行一次修正:

我刚发现网络上的其他任何设备都不会用于在网站上购买,因此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.");
        }
    };
});