简体   繁体   中英

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:fec4:3" and so on.

Could somebody give me some help?

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))

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

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM