[英]Check local (internal) IP with JavaScript
我知道这似乎是重复的,但老实说我无法找到任何解决方法。
我有两个iPad,它们在只能访问www.example.com的网络上设置了静态IP地址(网络限制,而不是iPad限制)。 example.com是一个电子商务网站,每当这两个iPad之一访问该网站时,我都想填写优惠券字段。
我能想到的唯一方法是获取iPad的本地IP地址(例如192.168.0.x)并创建白名单阵列。 但是我的问题是试图检测浏览设备的本地IP。
我无法使用example.com域之外的任何资源,也无法使用网络的公共IP,因为将会连接许多其他设备。
另外,我尝试过WebRTC,但仅适用于Chrome和Firefox,而且仅限于iPad的本地Safari浏览器。
帮我溢出Kenobi,您是我唯一的希望!
编辑
条件已经改变。 我发现没有其他设备将使用结帐服务,因此我现在可以定位外部IP。 有关如何执行此操作的详细信息如下。
好的,我找到了解决问题的方法。
首先纠正我的原始问题:
我刚刚发现,网络上的其他设备实际上都不会在网站上用于购买,因此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.");
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.