Generate Random IP with Python
Written on July 3rd , 2010 by Cody SniderIn need of an IP address on-the-fly that appears to be valid? Try this:
from random import randrange
def generateIP():
blockOne = randrange(0, 255, 1)
blockTwo = randrange(0, 255, 1)
blockThree = randrange(0, 255, 1)
blockFour = randrange(0, 255, 1)
print 'Random IP: ' + str(blockOne) + '.' + str(blockTwo) + '.' + str(blockThree) + '.' + str(blockFour)
if blockOne == 10:
return self.__generateRandomIP__()
elif blockOne == 172:
return self.__generateRandomIP__()
elif blockOne == 192:
return self.__generateRandomIP__()
else:
return str(blockOne) + '.' + str(blockTwo) + '.' + str(blockThree) + '.' + str(blockFour)
We’re skipping 10.x.x.x, 172.x.x.x and 192.x.x.x due to the fact that these are reserved address. RFC 1918
Version 2:
An elegant solution to serve the purpose of generating a random IP provided by Ben (explanation of changes listed in the comments below):
if __name__=="__main__":
not_valid = [10,127,169,172,192]
first = randrange(1,256)
while first in not_valid:
first = randrange(1,256)
ip = ".".join([str(first),str(randrange(1,256)),
str(randrange(1,256)),str(randrange(1,256))])
print ip