2

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?

user2864740
  • 60,010
  • 15
  • 145
  • 220
changzhi
  • 2,641
  • 9
  • 36
  • 46
  • [Take a look at this question](http://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits). You should be able to work out how to apply it for your desired format. – Kevin Jan 09 '14 at 10:02
  • The answer depends on the use case/purpose. Do you just want "something" which might qualify as an IPv6 address, or do you need one from a specific range (just the `fe80::` ones, all `f*` ones, or what). Not all ranges are defined. – glglgl Jan 09 '14 at 10:26
  • I have to take this method:` ip_v6 = 'fe80::' + random_str() + '1' `**def random_str(): import random seed = '1234567890abcdef' r_string = '' for b in range(3): for a in range(4): r_string = r_string + random.choice(seed) r_string = r_string + ':' return r_string** – changzhi Jan 09 '14 at 10:34

3 Answers3

7

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))
vmario
  • 411
  • 3
  • 15
  • Thank you for your answer. I have a question to ask you . Could you tell me what the mean of `{:x}` ? I know the mean of `:x` is hexadecimal . But I don't know the mean of `{}`... – changzhi Jan 10 '14 at 01:43
  • Curly braces `{}` are surround a "replacement field" in a format string for the `str.format()` method. It is something like the `%` symbol in format string used with the `%` string operator (or e.g. `printf()` in C language) - field surrounded by curly braces is replaced with `str.format()` argument. Please compare new [Format String Syntax](http://docs.python.org/3.3/library/string.html#format-string-syntax) with old [String Formatting Operations](http://docs.python.org/2/library/stdtypes.html#string-formatting-operations). – vmario Jan 10 '14 at 07:05
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

Community
  • 1
  • 1
Theox
  • 1,363
  • 9
  • 20
0

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)))
skyshock21
  • 101
  • 1