【问题标题】:Redirect ranges of IPs in JavaScript (no .htaccess)在 JavaScript 中重定向 IP 范围(无 .htaccess)
【发布时间】:2015-08-19 19:11:57
【问题描述】:

回答 - 如何在重定向中指定 IP 地址范围

【问题讨论】:

  • 变量ip从何而来?
  • 您可能应该在服务器代码中执行此操作,而不是在客户端。客户端可能位于防火墙或 NAT 之后,因此本地 IP 不是其公共 IP。
  • 变量 ip 来自不同的脚本 - 我将对其进行编辑。该脚本只是获取查看者的 IP 地址。

标签: javascript redirect ip


【解决方案1】:

使用正则表达式代替数组:

var blocklist = /^(10\.20\.30\.40|50\.60\.70\.80|123\.123\.123\..*)$/;
if (ip.match(blocklist)) {
    window.location.replace('http://fakeblock.com/');
}

【讨论】:

  • 我现在正在使用这个正则表达式。如何确保它捕获以 123.123.123 开头的所有 IP 地址,即从 123.123.123.0 到 123.123.123.255 的所有 IP 地址?
  • 啊等等,没关系。我正在使用这个: var warnlist = /^(123\.123\.123\.(25[0-5]|2[0-4][0-9]|[01]?[0-9] [0-9]?))$/;
  • 正则表达式末尾的 .* 匹配任何内容。没必要这么具体。
【解决方案2】:

我会编写一个函数来匹配 IP,它接受通配符。

/**
* Matches two ip's, supports the use of "wildcard", ex 192.168.*.*
*
* If an array of IP addresses is passed as the second argument, this
* function will return if any of them match.
*
* @param string A decimal separated IPv4 address
* @param string/[string] A, or an array of, decimal separated IPv4 addresses to match the first IP address against.
*/
function matchIP(ip, ipMatch) {
    if (ipMatch instanceof Array) {
        for (singleIpMatch in ipMatch) {
            if (matchIP(ip, singleIpMatch)) return true;
        }
        return false;
    }

    ipMatchParts = ipMatch.split('.');
    ipParts = ip.split('.');

    // IP is invalidly formatted 
    if (ipParts.length !== 4) {
        return false;
    }
    // IP match is invalidly formatted
    if (ipMatchParts.length !== 4) {
        return false;
    }

    matched = true;
    for (var i = 0; i < 4; i++) {
        if (ipParts[i] === '*') continue;
        if (ipMatchParts[i] === '*') continue;
        if (ipParts[i] === ipMatchParts[i]) continue;
        matched = false;
        break;
    }
    return matched
}

代码已经过测试并且可以工作,插入到您的示例中,它看起来像:

<!-- check incoming IP address -->
<script type = "text/javascript" src="http://l2.io/ip.js?var=ip"></script>

<!-- redirect list -->
<script type = "text/javascript">
        window.onload = init();
        function init() {
            var blocklist = ["10.*.*.*","11.87.70.*"]; // For example
            for (var i = 0; i < blocklist.length; i++) {
                if (matchIP(ip, blocklist[i])) {
                    window.location.replace('http://fakeblog.com/');
                    break;
                }
            }
        }
</script>

注意!

如果重定向是出于安全原因,您永远不应该在客户端执行此操作。例如,客户端可能根本没有运行 JavaScript,记住在客户端发生的一切都是一个选择,所以永远不要在客户端做安全事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-23
    • 2011-03-10
    • 1970-01-01
    • 2016-06-09
    • 2021-03-17
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多