python 根据网段随机生成IPv4地址

python 根据网段随机生成IPv4地址,第1张

def genIP(rule):  
    ip, maskLen = rule.split('/')
    parts = ip.split('.')
    
    # 补全ip,如 10.24 => 10.24.0.0
    while(len(parts) < 4):
        parts.append('0')
    
    # 将IP字符串转化成整数
    ipNum = 0
    for i in parts:
        ipNum = 256*ipNum + int(i)

    # 求出子网的起始和结束位置
    subnetLen = 32 - int(maskLen)
    assert(subnetLen > 1 and subnetLen < 32)
    ipStart = ipNum >> subnetLen << subnetLen   # 子网地址 
    ipEnd = ipStart + 2**(subnetLen) - 1  # 广播地址 
    
    # 整数转化成IP
    def IPNum2str(num):
        result = []
        while num >= 256:
            result.append(num % 256)
            num = num // 256
        result.append(num)
        result.reverse()
        return '.'.join([str(i) for i in result])
    
    import random
    return IPNum2str(random.randint(ipStart+1, ipEnd-1))

测试

rule = '10.8.24.2/24'
for _ in range(30):
    print(genIP(rule))

"""
10.8.24.77
10.8.24.195
10.8.24.57
10.8.24.89
10.8.24.17
10.8.24.79
10.8.24.109
10.8.24.220
10.8.24.26
10.8.24.209
10.8.24.188
10.8.24.185
10.8.24.150
10.8.24.84
10.8.24.8
10.8.24.156
10.8.24.107
10.8.24.41
10.8.24.134
10.8.24.6
10.8.24.205
10.8.24.126
10.8.24.90
10.8.24.22
10.8.24.48
10.8.24.21
10.8.24.65
10.8.24.66
10.8.24.141
10.8.24.108
"""

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/915567.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存