Generate Random Ipv6 Address
In Python, what should I do if I want to generate a random string in the form of an IP v6 address? For example: 'ff80::220:16ff:fec9:1', 'fe80::232:50ff:fec0:5', 'fe20::150:560f:fe
Solution 1:
One-line solution:
str(ipaddress.IPv6Address(random.randint(0, 2**128-1)))
Or handmade address (but consecutive sections of zeroes are not replaced with a double colon):
':'.join('{:x}'.format(random.randint(0, 2**16 - 1)) for i inrange(8))
Solution 2:
To generate a random hexadecimal character, you could use this :
random.choice('abcdef' + string.digits)
Then it should be simple enough to generate your string in the form of an IPv6 address.
You can also find more informations about random string generation here : Random string generation with upper case letters and digits in Python
Solution 3:
Adjust functions as needed, this is older python 2.x; but mostly native libraries.
import random, struct, socket
from random import getrandbits
print socket.inet_ntop(socket.AF_INET6, struct.pack('>QQ', getrandbits(64), getrandbits(64)))
Post a Comment for "Generate Random Ipv6 Address"