A simple method to generate random IP addresses using Python scripts

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.