Reputation: 875
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?
Upvotes: 4
Views: 8894
Reputation: 141
Scapy has a function built-in to generate random ipv6 addresses.
source = RandIP6("2000::cafe:*:*")
print source
Note that, if its messing around with zero's
, you need to add 2 lines in the broncode of scapy/volatile.py before line 286
if n == 0:
ip.append("0")
Upvotes: 0
Reputation: 9533
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.
Upvotes: 5
Reputation: 9533
Just using string formatting:
import random
random.seed()
print '2001::cafe:%x/64' % random.getrandbits(16)
Upvotes: 0
Reputation: 17680
import random
M = 16**4
"2001:cafe:" + ":".join(("%x" % random.randint(0, M) for i in range(6)))
Upvotes: 8