Thread: Help with IP Generation Algorithm.

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    220

    Help with IP Generation Algorithm.

    Ok....i'm having a bit of trouble with developing an algorithm for a program i'm making.

    My program is supposed to make my life easier when generating lists of IP's. It's final product will output ip's in a .txt file with a line break at the end.

    Now..what i'm having trouble with is developing the algorithm for the ip incrementation.. I can't seem to do it right...all the times i've tried to think of how exactly one would increment IP's it has been beyond me. Because i'm not incrementing just one number..i'm incrementing 4 seperate variables.

    Heres my code:
    Code:
    #include <iostream>//for io
    #include <fstream>//for ofstream
    #include <conio.h>//will use this later.
    #include <stdlib.h>//for exit();
    
    //start and end IP values.
    int start1, start2, start3, start4;
    int end1, end2, end3, end4;
    
    //Used to handle errors.
    int error( int errNum )
    {
      switch( errNum )
      {
        case 1:
        {
            std::cout << "\nYou must enter IP values, exiting now.";
            exit(1);
            break;
        }
        default:
            std::cout << "\nUnknown error, exiting now.";
            exit(1);
      }
    }
    
    //Used to generate IP's.
    int generate( int _start1, int _start2, int _start3, int _start4, int _end1, int _end2, int _end3, int _end4 )
    {
    //What I can't get a grasp on..
    }
    
    //Used to gather input.
    int input( int choice )
    {
      switch( choice )
      {
       case 1:
          std::cin >> start1 >> start2 >> start3 >> start4;
          break;
       case 2:
          {
          std::cin >> end1 >> end2 >> end3 >> end4;
          generate(start1, start2, start3, start4, end1, end2, end3, end4);
          break;
          }
       default:
          error(1);
      }
    }
    
    //Displays banner and calls input();
    void banner()
    {
        std::cout << "Welcome to IP Generator 1.0\n\n";
        std::cout << "Enter in the first IP: ";
        input(1);
        std::cout << '\n';
        std::cout << "Enter in the second IP: ";
        input(2);
    }
    
    void write()
    {
    //will fill in later.
    }
    
    int main()
    {
    while (1)
    {
      banner();
      generate( start1, start2, start3, start4, end1, end2, end3, end4 );
    }
    return 0;
    }
    Sorry if thats a bit long of code, but I would guess you would ask for the code anyways..

    What I want to do..is increment the IP from the start value to the end value and put each ip into a temporary array, and then call write() to put it into a text file, and then start the whole process over again with the next IP.

    The writing isn't that big of a deal it's the ip generation algorithm that confuses me.. Eventually what i'll do, is create another array and use the '.' as a seperator with each entry and just write that to the text file with ofstream..thats no biggie. Any ideas?

    I really appretiate the help...
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Here's some sample C code to generate IPs in a range:
    Code:
    #include <stdio.h>
    
    typedef union IPv4
    {
      
      unsigned char quad[ 4 ];
      unsigned int  uint;
      
    } IPv4;
    
    int main( void )
    {
    
      union IPv4 start_ip;
      union IPv4 end_ip;
      
      start_ip.quad[ 3 ] = 192;
      start_ip.quad[ 2 ] = 168;
      start_ip.quad[ 1 ] = 0;
      start_ip.quad[ 0 ] = 0;
      
      end_ip.uint = start_ip.uint;
      end_ip.quad[ 1 ] = 255;
      end_ip.quad[ 0 ] = 255;
      
      while( start_ip.uint < end_ip.uint )
        {
          
          printf( "%d.%d.%d.%d\n", start_ip.quad[ 3 ], start_ip.quad[ 2 ], start_ip.quad[ 1 ], start_ip.quad[ 0 ] );
          start_ip.uint++;
          
        }
      
    
      return 0;
      
    }
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    Could you explain your code please? And possibly an example in c++?

    C is completely foreign to me..I can't really decipher that.
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >C is completely foreign to me..I can't really decipher that.
    The relevant parts are valid C++. Pull out your handy dandy reference text and read up on unions.
    My best code is written with the delete key.

  5. #5
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    If you're just generating them as text, it's no big deal. 4 nested for loops should do it.

    Code:
    std::ofstream file("generatedIPs.txt");
    
    for(int a = start1; a <= end1; ++a)
        for(int b = start2; b <= end2; ++b)
            for(int c = start3; c <= end3; ++c)
                for(int d = start4; d <= end4; ++d)
                    file << a << '.' << b << '.' << c << '.' << e << std::endl;
    No temporary array needed, as far as I can see.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  6. #6
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    Thank you Hunter2, I had a feeling thats all it was..bleh :-/
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  7. #7
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    @Hunter2: Bzzzt. Wrong. Try your code to generate all IPs between 192.168.200.1 and 192.168.300.1. The output will look like this:
    Code:
    192.168.200.1
    192.168.201.1
    192.168.202.1
    192.168.203.1
    ...
    192.168.299.1
    192.168.300.1
    Oh, I fixed my code to work properly, btw. Here it is:
    Code:
    #include <stdio.h>
    
    typedef union IPv4
    {
      
      unsigned char quad[ 4 ];
      unsigned int  uint;
      
    } IPv4;
    
    int main( void )
    {
    
      union IPv4 start_ip;
      union IPv4 end_ip;
      
      start_ip.quad[ 3 ] = 192;
      start_ip.quad[ 2 ] = 168;
      start_ip.quad[ 1 ] = 0;
      start_ip.quad[ 0 ] = 0;
      
      end_ip.uint = start_ip.uint;
      end_ip.quad[ 1 ] = 255;
      end_ip.quad[ 0 ] = 255;
      
      while( start_ip.uint <= end_ip.uint )
        {
          
          printf( "%d.%d.%d.%d\n", start_ip.quad[ 3 ], start_ip.quad[ 2 ], start_ip.quad[ 1 ], start_ip.quad[ 0 ] );
          start_ip.uint++;
          if( !start_ip.uint ) break;
          
        }
      
    
      return 0;
      
    }
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  8. #8
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    I am a big fan of XSquared's solution, however here is the same solution done very crudely. Hopefully it will help illustrate how to do what you need to.
    Code:
    #include <iostream>
    using namespace std;
    
    int main() {
      int   dial = 3;
      short bytes[4] = { 0 };
    
      bool done = false;
    
      while (!done) {
        cout << bytes[0] << '.' << bytes[1] << '.' << bytes[2] << '.' << bytes[3] << endl;
      
        for (int i = 3; i >= dial; --i) {
          if (bytes[i] < 255) {
            ++bytes[i];
            break;
          }
          else {
            bytes[i] = 0;
            if (i == dial) {
              if (i == 0) {
                done = true;
                break; 
              }
    
              ++bytes[--dial];
              break;
            }
          }
        }
      }
      
      return 0;
    }
    Think of it as the dial on the speedometer in your car. Starting on the right the first digit goes from 0-9 then it goes back to zero and when it does, the next digit up goes up one and it continues. Get it?

  9. #9
    Registered User heat511's Avatar
    Join Date
    Dec 2001
    Posts
    169
    so unions are kinda like structs in c++?

    EDIT: nm just read up on em... cool
    Last edited by heat511; 04-06-2004 at 01:31 PM.
    "uh uh uh, you didn't say the magic word"
    -Jurassic Park

  10. #10
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    @Hunter2: Bzzzt. Wrong. Try your code to generate all IPs between 192.168.200.1 and 192.168.300.1.
    Judging from the fact that the function had start/end parameters for each of the four bytes, I'd assumed that that was what he'd been after - listing the ip's with the xth byte between startx and endx.

    Just felt that I needed to defend the working-as-intended-ness of my code Although just to speculate, who might have an IP address of 192.168.300.1?...

    **note: I'm a big fan of your solution too, now that I understand the question properly
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  11. #11
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    The only problem i'm having is that it doesn't increment to 255..you know what I mean?
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  12. #12
    Registered User
    Join Date
    Apr 2004
    Posts
    21
    hi buddy ,
    your life gets easiere if u use available api to generate random ip address like libnet

  13. #13
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>to generate random ip address
    Why would you need to do that?

    @Tronic:
    Sorry, no I don't really get what you mean (I'm too lazy to compile the code and find out myself ).
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  14. #14
    Registered User
    Join Date
    Jan 2003
    Posts
    648
    Why not replace that code inside your loops with this?
    Code:
    SaveFile << o << '.' << p << '.' << k << '.' << i << endl;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting 32 bit binary IP to decimal IP (vice-versa)
    By Mankthetank19 in forum C Programming
    Replies: 15
    Last Post: 12-28-2009, 07:17 PM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM