One possible solution:
import random
MAX_IPV4 = ipaddress.IPv4Address._ALL_ONES # 2 ** 32 - 1
MAX_IPV6 = ipaddress.IPv6Address._ALL_ONES # 2 ** 128 - 1
def random_ipv4():
return ipaddress.IPv4Address._string_from_ip_int(
random.randint(0, MAX_IPV4)
)
def random_ipv6():
return ipaddress.IPv6Address._string_from_ip_int(
random.randint(0, MAX_IPV6)
)
Examples:
>>> random.seed(444)
>>> random_ipv4()
'79.19.184.109'
>>> random_ipv4()
'3.99.136.189'
>>> random_ipv4()
'124.4.25.53'
>>> random_ipv6()
'4fb7:270d:8ba9:c1ed:7124:317:e6be:81f2'
>>> random_ipv6()
'fe02:b348:9465:dc65:6998:6627:1300:29c9'
>>> random_ipv6()
'74a:dd88:1ff2:bfe3:1f3:81ad:debd:db88'
If ipaddress
is optional, you can use this
>>> import random
>>> import socket
>>> import struct
>>> socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
'197.38.59.143'
>>> socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
'228.237.175.64'
If you want multiple IPs, put it in a loop like this,
for _ in range(10):
print(socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff))))
Output:
151.166.184.41
237.59.227.33
249.179.144.26
248.151.116.150
94.186.44.162
251.238.134.106
5.239.51.182
198.1.81.192
24.116.237.239
187.8.43.55