First Script Problem
Brett g Porter
bgporter at acm.org
Fri Sep 16 16:01:54 EDT 2005
Ed Hotchkiss wrote:
> This script should just be writing every possibly IP (yea, there are
> billions i know blah blah) to a txt file. Instead of just writing the
> IP, it continues and the number goes past 4 groups. IE: The possible IP
> keeps getting 3 characters longer every time. And at the end of the last
> loops do I somehow have to set my mySet to NULL? Any ideas here?
>
> --
> edward hotchkiss
>
>
>
>
>
> # Script to Evaluate every possible IP Address Combo, then write it to a
> text file
> # 9/15/05
>
> # ipFileLocation = r"G:\Python\myCode\IPList.txt"
>
> ipFileLocation = "IPList.txt"
> ipFile = open(ipFileLocation, 'w')
>
> def findIPs():
> for num in range(256):
> mySet = "%03.d" % num
okay -- at this point, on the first iteration of this outer loop, mySet
is '000'
> for num in range(256):
> mySet = mySet + "." + "%03.d" % num
and on the first iteration of this first inner loop, mySet is '000.000'
> for num in range(256):
> mySet = mySet + "." + "%03.d" % num
second inner loop, first iteration, mySet is '000.000.000'
> for num in range(256):
> mySet = mySet + "." + "%03.d" % num
> ipFile.write(mySet+"\n")
Okay -- this innermost loop will now be executed 256 times (values
ranging from 0 to 255, and mySet just keeps getting appended to,
creating the ever-growing output string that you see.
A better way to write this would be something like:
for octet1 in range(256):
for octet2 in range(256):
for octet3 in range(256):
for octet4 in range(256):
ipAddress = '%03.d.%03.d.%03.d.%03.d\n' % (octet1, octet2,
octet3, octet4)
ipFile.write(ipAddress)
...which will generate output like you're looking for:
000.000.000.000
000.000.000.001
000.000.000.002
000.000.000.003
000.000.000.004
000.000.000.005
000.000.000.006
000.000.000.007
000.000.000.008
000.000.000.009
000.000.000.010
000.000.000.011
000.000.000.012
000.000.000.013
000.000.000.014
Also note that growing strings by concatenating with '+' is going to
create code that runs very slowly as the strings continue to grow --
much better to either use string formatting or the idiom of using the
join method of list objects to create a string in a single pop once a
list of substrings is all populated.
--
// Today's Oblique Strategy (© Brian Eno/Peter Schmidt):
// Destroy -nothing -the most important thing
// Brett g Porter * BgPorter at acm.org
// http://bgporter.inknoise.com/JerseyPorkStore
More information about the Python-list
mailing list