如何循环并构建 IP 地址

How to loop around and build an IP Address

给定 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,依此类推。

因此,您不想通过拆分 '%' 字符来递增。最好按八位字节分割:

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);
      }
   }
}

这个版本的 anser 使用递归来创建 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( '.' ) );
  }
}