Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random IPv6 address using Python(or in Scapy)?

In my test case, I need to send out NA with random IPv6 source address and fixed prefix. For example:

fixed prefix 2001::cafe:/64. The remainder of the address should be random.

How to achieve in Python or in Scapy?

like image 661
deepsky Avatar asked Oct 18 '25 14:10

deepsky


2 Answers

import random   
M = 16**4
"2001:cafe:" + ":".join(("%x" % random.randint(0, M) for i in range(6)))
like image 188
Ruggero Turra Avatar answered Oct 21 '25 05:10

Ruggero Turra


Not sure from the question which parts of the address you want to be random. I'm assuming the last 2 bytes.

Using the python netaddr library:

import random
from netaddr.ip import IPNetwork, IPAddress

random.seed()
ip_a = IPAddress('2001::cafe:0') + random.getrandbits(16)
ip_n = IPNetwork(ip_a)
ip_n.prefixlen = 64

print ip_a
print ip_n

Sample output:

2001::cafe:c935
2001::cafe:c935/64

The advantage over simple string formatting, is it would be easy to customize the starting address, random bit len. Also the netaddr classes have many useful attr, e.g. the broadcast address of the network.

like image 36
Gary van der Merwe Avatar answered Oct 21 '25 03:10

Gary van der Merwe