简体   繁体   English

我该如何重写此功能,而不必显式键入范围内的每个IP地址?

[英]How can I rewrite this function so I don't have to explicitly type out every IP address within a range?

I want to run a certain script based on a set of IP's that have been given to me. 我想根据提供给我的一组IP运行特定的脚本。

The script I have below works just fine, however it seems sloppy and like too much code for what I want to accomplish. 我下面的脚本可以正常工作,但是它看起来很草率,并且喜欢要完成的代码太多。

I have simplified the number of IP addresses so as not to clutter up the screen. 我简化了IP地址的数量,以免使屏幕混乱。

<script>
    //Initialize the array
    //HostMin: 196.145.179.129  HostMax:   196.145.179.130            
    var $ipArray = ["196.145.179.129","196.145.179.130"];
    //HostMin: 50.207.77.201  HostMax:   50.207.77.204            
    $ipArray.push("50.207.77.201","50.207.77.202","50.207.77.203","50.207.77.204");
    //HostMin: 57.179.277.209  HostMax:   57.179.277.214       
    $ipArray.push("57.179.277.209","57.179.277.210","57.179.277.211","57.179.277.212","57.179.277.213","57.175.277.214");
    //HostMin: 74.97.164.65  HostMax:   74.97.164.66       
    $ipArray.push("74.97.164.65","74.97.164.66");

    $ipAddr = "74.97.164.65";

    if ($.inArray($ipAddr, $ipArray ) >= 0) {
        //Do Something
    }else{
        //Do Something else
    }
</script>    

I do have info such as an IP Filter - 50.207.77.201/30 if this makes a difference. 我确实有IP过滤器之类的信息50.207.77.201/30如果有区别)。

Any help in rewriting this would be appreciated. 重写任何帮助,将不胜感激。

I am not a smart man and posted a PHP response. 我不是一个聪明人,并发布了一个PHP响应。 Since others in this thread have mentioned my answer I will not delete it. 由于此线程中的其他人提到了我的答案,因此我不会删除它。 You could theoretically use this function and the basic logic of my answer in Javascript though: 从理论上讲,您可以使用此函数和我的Java回答的基本逻辑:

function ip2long (IP) {
  // http://kevin.vanzonneveld.net
  // +   original by: Waldo Malqui Silva
  // +   improved by: Victor
  // +    revised by: fearphage (http://http/my.opera.com/fearphage/)
  // +    revised by: Theriault
  // *     example 1: ip2long('192.0.34.166');
  // *     returns 1: 3221234342
  // *     example 2: ip2long('0.0xABCDEF');
  // *     returns 2: 11259375
  // *     example 3: ip2long('255.255.255.256');
  // *     returns 3: false
  var i = 0;
  // PHP allows decimal, octal, and hexadecimal IP components.
  // PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components.
  IP = IP.match(/^([1-9]\d*|0[0-7]*|0x[\da-f]+)(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?$/i); // Verify IP format.
  if (!IP) {
    return false; // Invalid format.
  }
  // Reuse IP variable for component counter.
  IP[0] = 0;
  for (i = 1; i < 5; i += 1) {
    IP[0] += !! ((IP[i] || '').length);
    IP[i] = parseInt(IP[i]) || 0;
  }
  // Continue to use IP for overflow values.
  // PHP does not allow any component to overflow.
  IP.push(256, 256, 256, 256);
  // Recalculate overflow of last component supplied to make up for missing components.
  IP[4 + IP[0]] *= Math.pow(256, 4 - IP[0]);
  if (IP[1] >= IP[5] || IP[2] >= IP[6] || IP[3] >= IP[7] || IP[4] >= IP[8]) {
    return false;
  }
  return IP[1] * (IP[0] === 1 || 16777216) + IP[2] * (IP[0] <= 2 || 65536) + IP[3] * (IP[0] <= 3 || 256) + IP[4] * 1;
}

Hopefully someone smarter than me (low bar) will post a better answer for you. 希望有人比我聪明(下限)将为您提供更好的答案。


I have found the ip2long function is perfectly suited for this use case 我发现ip2long函数非常适合此用例

$low     = ip2long($low_address);
$high    = ip2long($high_address);
$user_ip = ip2long($_SERVER['REMOTE_ADDR']);

if($user_ip >= $low && $user_ip <= $high){
    // do something
}

This answer does not completely answer the OP question but rather augments Rob M's existing answer. 该答案不能完全回答OP问题,而是可以增强Rob M的现有答案。 It provides a simpler, faster function that does most of the work. 它提供了一个简单,快速的功能,可以完成大部分工作。

JavaScript function to convert an IP address to a 32-bit unsigned integer JavaScript函数将IP地址转换为32位无符号整数

// Convert an IPv4 dotted quad address to unsigned 32-bit integer
// Return FALSE if IP address is not well formed
function ip2int(ip) {
    var val = false,        // Assume passed IP is invalid.
        // Regex to validate and parse an IP (version 4) address.
        re_valid_ipv4       = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    // Use String.replace() with callback to validate and parse in one whack.
    ip.replace(re_valid_ipv4,   
        function(m0,m1,m2,m3,m4){
            val = ((m1 << 24) + (m2 << 16) + (m3 << 8) + (+m4)) >>> 0;
            return '';
        });
    return val;
}

I found an iplib.js that might just be perfect for you. 我发现了一个iplib.js ,可能对您来说很完美。

In their usage wiki , they talk about iterating over a network (by using a subnet mask, not by actually interacting with the network) and I think it'll meet your needs perfectly. 在他们的用法Wiki中 ,他们谈论通过网络进行迭代(通过使用子网掩码,而不是通过实际与网络交互),我认为这将完全满足您的需求。

   var ip = new IPv4("192.168.0.100");
   var subnet = new Subnet("/24");

   var ipnet = new IPv4Network(ip,subnet);

   var network = ipnet.network();     //IPv4("192.168.0.0")
   var broadcast = ipnet.broadcast(); //IPv4("192.168.255.255");

   var stopIP = new IPv4("192.168.0.10");
   range_ips = [];                
   ipnet.iter(function(ip,index) {
       range_ips.push(ip);
       if(ip.equals(stopIP)) return false;
   });

   //check IPs are in a network
   var is_contained = ipnet.contains(ip)           //true;
   var total = ipnet.count();                      //254

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确保将计时器设置为每天4点半,所以我不必在Javascript中提及某个日期? - How can I make sure the timer is set to half 4 every day, so I don't have to mention a certain date in Javascript? 我该如何重写此javascript代码,以便它将引用每个optionbox? - How can I rewrite this javascript code, so that it will refer to every optionbox? 试图简化这个功能,所以我不必运行它 9 次 - Trying to simplify this function so I don't have to run it 9 times 我该如何进行变量设置,以免在以后的功能中重复自己 - How can I make variables so that I don't have to repeat myself in future functions 我该如何修改此代码,以便不必对对象进行排序? - How can I amend this code so that I don't have to sort an Object? 我怎样才能更改我的代码,以便我不必为所有单个记录使用脚本? - How can I change my code so that I don't have to use a script for all single record? TypeScript:对于这个 function,如何将类型显式传递给 generics - TypeScript: How can I explicitly pass in the type to the generics for this function 如何重写此代码,以便Closure Compile重命名我的函数? - How can I rewrite this so that Closure Compile renames my function? 如何将后面代码中的循环创建的 Javascript 函数组合到一个函数中,这样我就不必重复了? - How could I combine Javascript functions created by a loop in the code behind in to one function so I don't have to repeat? 使用angular 2 CLI,如何使用绝对路径,所以不必使用来自&#39;../../../shared/thing&#39;的import {..} - using angular 2 CLI, how can I use absolute paths so I don't have to use import { .. } from '../../../shared/thing'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM