Python: IP address random
i'm working right now over one interesting test case and I need generate random IP address.
For my test case I will use second variant but you can use anyone from those two whenever you need.
[code language="python"]
import random
print("test 1")
# IP's min and max number
ip = ".".join(map(str, (random.randint(0, 255)
# will generate 4 group of numbers "xxx.xxx.xxx.xxx"
for _ in range(4))))
print ip
# or
print("\ntest 2")
# generated randomly 10 ip addresses
for x in xrange(1,10):
# IP address will begin ...
ip = "170.12."
# IP's min and max number
ip += ".".join(map(str, (random.randint(0, 255)
# will generate last two group of numbers "xxx.xxx"
for _ in range(2))))
print ip
# Validator -------------------------------------------------------------
# IP address validator: v1
def validate_ip(s):
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
# IP address validator: v2
import socket
try:
socket.inet_aton(addr)
# legal
except socket.error:
# Not legal
# IP address validator: v3
from IPy import IP
try:
ip = IP('230.10.10.16')
except ValueError:
# invalid IP
'''
Done!
'''
[/code]
For my test case I will use second variant but you can use anyone from those two whenever you need.
[code language="python"]
import random
print("test 1")
# IP's min and max number
ip = ".".join(map(str, (random.randint(0, 255)
# will generate 4 group of numbers "xxx.xxx.xxx.xxx"
for _ in range(4))))
print ip
# or
print("\ntest 2")
# generated randomly 10 ip addresses
for x in xrange(1,10):
# IP address will begin ...
ip = "170.12."
# IP's min and max number
ip += ".".join(map(str, (random.randint(0, 255)
# will generate last two group of numbers "xxx.xxx"
for _ in range(2))))
print ip
# Validator -------------------------------------------------------------
# IP address validator: v1
def validate_ip(s):
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
# IP address validator: v2
import socket
try:
socket.inet_aton(addr)
# legal
except socket.error:
# Not legal
# IP address validator: v3
from IPy import IP
try:
ip = IP('230.10.10.16')
except ValueError:
# invalid IP
'''
Done!
'''
[/code]
Comments
Post a Comment