使用Python指令碼產生隨機IP的簡單方法

來源:互聯網
上載者:User
需求

在某應用中,需要根據一定的規則產生隨機的IP地址,規則類似於192.168.11.0/24這樣的CIDR形式給出。
實現

經過艱苦卓絕的調試,下面的代碼是可以用的:

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)))

產生的結果如:

 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 

備忘

(mask & 0xffffffff)這一用法,目的在於消除mask上32位以上的高位元據。由於mask是IPv4的掩碼,所以不需要32位以上的資料。這一問題在mask取反之後比較明顯。由於mask是一個32位以上的數(有可能是64位),取反之後,高位全部為1,計算的結果就不正確了。因此,在使用之前,需要利用(mask & 0xffffffff)清除高位。

供各位讀者參考。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.