Search code examples
javascriptfor-loopip-address

How to loop around and build an IP Address


Given 1.1.%.%, where % is a wildcard, I want to loop through all possible IP addresses.

So far I have been able to replace one % successfully with a loop, but when I attempt to try to replace 2, it simply replaces it with the same number. The following is the code I have at the moment, any help on how to put in this second loop to get the second % would be appreciated.

Code:

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

Output from this is 1.1.0.0, then 1.1.1.1, etc.


Solution

  • This version of an anser uses recursion to perform the IP creations. It splits on the decimals, and then recursively goes through the tokens to see if they are % or not, and if they are will interchange them for [0, tokenLimit] until it exhausts all possibilities.

    For the sake of not blowing up the browser, I set the tokenLimit to 11, rather than 255. Comments have been added to the logic for detailed explanations.

    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( '.' ) );
      }
    }