【问题标题】:How to loop around and build an IP Address如何循环和建立 IP 地址
【发布时间】:2019-08-11 07:09:00
【问题描述】:

给定 1.1.%.%,其中 % 是通配符,我想遍历所有可能的 IP 地址。

到目前为止,我已经能够用循环成功替换 1%,但是当我尝试替换 2 时,它只是用相同的数字替换它。以下是我目前拥有的代码,任何有关如何放入第二个循环以获得第二个 % 的帮助将不胜感激。

代码:

var wildCount = inputSt.match(/\%/g)  //works out how many % are there
var newPlaceholder ='' 
for (var i = 0; i < wildCount.length; i++){
    newPlaceHolder =inputSt.split("%").join(i)
    for (var n = 0; n <=254; n++){
        newPlaceholder = inputSt.split("%").join(n)
     }
 }

由此产生的输出是 1.1.0.0,然后是 1.1.1.1,等等。

【问题讨论】:

    标签: javascript for-loop ip-address


    【解决方案1】:

    此版本的分析器使用递归来执行 IP 创建。它按小数分割,然后递归地遍历令牌以查看它们是否为 %,如果它们将它们交换为 [0, tokenLimit] 直到耗尽所有可能性。

    为了不炸毁浏览器,我将 tokenLimit 设置为 11,而不是 255。逻辑中已添加注释以进行详细说明。

    var test = '1.1.%.%';
    var tokens = test.split( '.' );
    var tokenLimit = 11;
    
    // start the recursion loop on the first token, starting with replacement value 0
    makeIP( tokens, 0, 0 );
    
    function makeIP ( tokens, index, nextValue ) {
      // if the index has not advanced past the last token, we need to
      // evaluate if it should change
      if ( index < tokens.length ) {
        // if the token is % we need to replace it
        if ( tokens[ index ] === '%' ) {
          // while the nextValue is less than our max, we want to keep making ips
          while ( nextValue < tokenLimit ) {
            // slice the tokens array to get a new array that will not change the original
            let newTokens = tokens.slice( 0 );
            // change the token to a real value
            newTokens[ index ] = nextValue++;
            
            // move on to the next token
            makeIP( newTokens, index + 1, 0 );
          }
        } else {
          // the token was not %, move on to the next token
          makeIP( tokens, index + 1, 0 );
        }
      } else {
        // the index has advanced past the last token, print out the ip
        console.log( tokens.join( '.' ) );
      }
    }

    【讨论】:

    • 请注意,堆栈溢出显示的控制台日志似乎并未显示所有日志。运行时查看实际的浏览器控制台。
    【解决方案2】:

    因此,您不想通过拆分“%”字符来增加。最好按八位字节拆分:

    var octets = inputSt.split('.');
    

    那里有 0-3 个八位字节(因为它是一个数组)。然后,您可以执行递归 if 语句检查通配符并随时递增。

    for (var i = 0; i < octets.length; i++) {
       if (octets[i].match('%')) {
          Do some incrementing...
       }
    }
    

    显然,这段代码还没有完成。但它应该能让你朝着正确的方向前进。

    提示 - 您希望支持 1-4 个通配符。所以最好创建一个增加单个八位字节的函数。如果八位组不是带有通配符的最后一个八位组,则再次调用相同的函数。该功能的肉如下。我会让你弄清楚在哪里以及如何执行单个递增。:

    function incrementOctet(octet) {
       if (octet < 3) {
          if (octets[octet + 1].match('%')) {
             incrementOctet(octet + 1);
          }
       }
    }
    

    【讨论】:

    • 谢谢!出于几个原因,我实际上只允许用户在输入中使用 2 个通配符,主要是因为它们匹配的数据量。
    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    相关资源
    最近更新 更多