如何循环并构建IP地址

3

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

到目前为止,我已经成功地用一个循环替换了一个%,但是当我尝试尝试替换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等等。

2个回答

2
这个答案使用递归来执行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( '.' ) );
  }
}


1
请注意,Stack Overflow 显示的控制台日志似乎没有显示所有日志。运行时,请查看您实际的浏览器控制台。 - Taplar

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

谢谢!出于多种原因,我只允许用户在输入中使用2个通配符,主要是因为它们匹配的数据量。 - Uciebila

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接