This article mainly introduces a simple method to generate random IP addresses using Python scripts, and you can set the IP address value range by yourself. For more information, see
Requirement
In an application, you need to generate random IP addresses according to certain rules. The rules are given in a CIDR format similar to 192.168.11.0/24.
Implementation
After arduous debugging, the following code can be used:
RANDOM_IP_POOL=['192.168.10.222/0']def __get_random_ip(): str_ip = RANDOM_IP_POOL[random.randint(0,len(RANDOM_IP_POOL) - 1)] str_ip_addr = str_ip.split('/')[0] str_ip_mask = str_ip.split('/')[1] ip_addr = struct.unpack('>I',socket.inet_aton(str_ip_addr))[0] mask = 0x0 for i in range(31, 31 - int(str_ip_mask), -1): mask = mask | ( 1 << i) ip_addr_min = ip_addr & (mask & 0xffffffff) ip_addr_max = ip_addr | (~mask & 0xffffffff) return socket.inet_ntoa(struct.pack('>I', random.randint(ip_addr_min, ip_addr_max)))
The generated result is as follows:
192.168.10.175 192.168.10.29 192.168.10.30 192.168.10.207 192.168.10.248 192.168.10.145 192.168.10.168 192.168.10.223 192.168.10.66 192.168.10.138 192.168.10.99 192.168.10.136 192.168.10.147 192.168.10.244 192.168.10.73 192.168.10.180
Remarks
(Mask & 0 xffffffff) is used to eliminate high data with more than 32 bits on the mask. Because the mask is an IPv4 mask, you do not need more than 32 bits of data. This problem is obvious after the mask is reversed. Because the mask is a number more than 32 bits (may be 64 bits), after the inverse is obtained, all the high positions are 1, and the calculation result is incorrect. Therefore, before use, use (mask & 0 xffffffff) to clear the high position.
For your reference.