Reputation: 2709
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:fec4:3" and so on.
Could somebody give me some help?
Upvotes: 2
Views: 3943
Reputation: 101
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)))
Upvotes: 0
Reputation: 411
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 in range(8))
Upvotes: 7
Reputation: 1363
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
Upvotes: 2