skip to main | skip to sidebar

Python Programs and Examples

Pages

  • Home
 
  • RSS
  • Facebook
  • Twitter
Sunday, October 21, 2012

IP Address Generation

Posted by Raju Gupta at 4:39 AM – 0 comments
 

The script asks the user for two IP addresses . One is the start of the IP range, and the second is the end of it. Next, a new IP object is created using the defined IP class called i . The final step before generating the IPs is to initialize the file the IP addresses will be written to, named ofile . Now the fun begins.

For each item returned, the results will be output to ofile. Using the IP class method succ!, an until loop calls the succ! method until i equals end_ip . Once the two values are equal, that means the ending IP address has been generated and the output file is closed.

The script relies on a custom class called IP, which has four methods: initialize, to_s, succ, and succ!. The IP class is important because, once an object is created, the IP address is stored as a class variable for easy tracking. The first method called, when i is declared, is initialize. This sets @ip to start_ip . Next, succ! is called to begin creating the range of IPs. succ! calls succ and utilizes the replace method to overwrite the contents in @ip whenever succ returns a value . The meat of the IP class is located in the method succ . If @ip ever increments to the highest IP address, the script will return 255.255.255.255. IP addresses can only go up to that value.

Next, the IP address, stored in @ip, is split apart in reverse order, using the period as a delimiter. The values are stored in an array called parts. After the IP address is properly separated, a new code block is called on the array using the each_with_index method to access two pieces of informationâ??the index being passed and the value . Within this block, the value in part is compared against 255, again to prohibit invalid IP addresses. If the value is equal to 255, then it is reset to zero . The one exception to the zero reset is if the value of i is equal to 3, since that is the first octet of the IP. If part is less than 255, the method succ! is called and the if/else statement breaks.

After each part has been run through the code block, the IP address is put back together opposite of how it was taken apart. The script puts each piece back together using the join method, with periods in between the elements, all in reverse order . As mentioned previously, the succ! method is called until the end_ip address is equal to the results of succ!. That's all there is to perfectly generating an IP address range.


class IP
     def initialize(ip)
         @ip = ip
     end

     def to_s
         @ip
     end

     def==(other)
         to_s==other.to_s
     end

     def succ
         return @ip if @ip == "255.255.255.255"
         parts = @ip.split('.').reverse
         parts.each_with_index do |part,i|
             if part.to_i < 255
                 part.succ!
                 break
             elsif part == "255"
                 part.replace("0") unless i == 3
             else
                 raise ArgumentError, "Invalid number #{part} in IP address"
             end
         end
         parts.reverse.join('.')
     end

     def succ!
         @ip.replace(succ)
     end
 end

 print "Input Starting IP Address: "
 start_ip = gets.strip 

 print "Input Ending IP Address: "
 end_ip = gets.strip

 i = IP.new(start_ip)

 ofile = File.open("ips.txt", "w")
 ofile.puts i.succ! until i == end_ip
 ofile.close


Labels: Python Network Example Email This BlogThis! Share to X Share to Facebook

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments (Atom)
  • Popular
  • Recent
  • Archives

Popular Posts

  • To Send the entire contents of directory as an email Message.
    Here is a Python Program to send the entire contents of a directory as an email message #!/usr/bin/env python """Send the...
  • Control Structures in Python
    This Program explains different control structures in python If ==== # basic "If" if boolean: x = 1 else: x = 0 # No...
  • Python Code for creating Screen saver
    This is the Python code for creating a screensaver of a moving ball. The ball will bee moving along the screen and when it hits any of the ...
  • Python script for walking the directory tree structure but excluding some directories and files
    The script walks the directory structure recursively. Some of the directories and files can be excluded from the walk by providing them in ...
  • XML to CSV Converter
    Python Program to extract each execution data (few children in xml) and create a csv file. def xml2csv(inputFile,outputFile,elemName,n...
  • HTML Email using Python
    We created a module called sendmail which email html content. Each of application dumps data from the datastructure into html format and th...
  • Overview of Python Programming Language
    Python is an easy to learn, powerful programming language. It has efficient high level data structures and a simple but effective approac...
  • Fast and efficient Backup script that works on Windows and Linux
    This python script backup your directory structure that works on Linux and Windows both. It directly uses the shell to do this task and she...
  • Run Application from host
    import os os.execl( "c:/Windows/Notepad.exe", "c:/userlog.txt") print "Running notepad" #or import subpro...
  • Orphan Checker
    The script does not use any outside libraries, thus keeping its execution simple. we will start by initializing the arrays that we'll...
Powered by Blogger.

Archives

  • ▼  2012 (66)
    • ▼  October (28)
      • Find text/pattern under parent folder from matched...
      • XML to CSV Converter
      • XSL to CSV converter
      • Spell Corrector in Python
      • Format a plain ASCII file using Python script
      • Control Structures in Python
      • Python script to zip and unzip files
      • Fast and efficient Backup script that works on Win...
      • File Splitter Script
      • Python script for walking the directory tree struc...
      • Python XML Parser
      • IP Address Generation
      • Orphan Checker
      • HTML Email using Python
      • Python interface to load commands.
      • Python script to Validate Tabular format Data and ...
      • Python script to Load Configuration file content i...
      • Python Script to search file for specific content
      • Network Wise File Concatenation
      • Python Script for Adding or Subtracting the Dates
      • Program to create make file in VMS/UNIX
      • Python Code for creating Screen saver
      • Run Application from host
      • Multithreading in Python
      • This utility determines the size of a folder and i...
      • Using UNIX Environment Variables From Python
      • CVS Macro for Commited Files
      • Generating unique id's
    • ►  September (36)
    • ►  March (1)
    • ►  February (1)
 

Labels

  • Command Execution Using Python (2)
  • Control Structure (1)
  • CSV Examples (4)
  • Database (3)
  • Features of Python Programming Language (1)
  • File Example (2)
  • IF Statement (1)
  • List (2)
  • Mail (5)
  • Multithreading (1)
  • MySQL (3)
  • Python Date Example (2)
  • Python Example (2)
  • Python File Example (7)
  • Python Introduction (1)
  • Python Network Example (1)
  • Python XML Parser (2)
  • Searching Example (2)
  • Simple Calculation Program (1)
  • Strings (4)
  • Zip File Example (1)

Followers

 
 
© 2011 Python Programs and Examples | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger