防止函数生成专用地址

2024-04-26 18:32:12 发布

您现在位置:Python中文网/ 问答频道 /正文

如何防止这个python生成私有地址?你知道吗

def gen_ip():
    b1 = random.randrange(0, 255, 1)
    b2 = random.randrange(0, 255, 1)
    b3 = random.randrange(0, 255, 1)
    b4 = random.randrange(0, 255, 1)
    ip = str(b1)+"."+str(b2)+"."+str(b2)+"."+str(b4)
    ip = ip[::-1]
    return ip

Tags: ipreturn地址defrandomb2b1b3
3条回答
def isPrivateIp (ip):
    # fill this
    return True or False

ip = gen_ip()
while isPrivateIp(ip):
    ip = gen_ip()

我觉得波克的回答很好。但如果要在循环中生成和使用这些,我只需要创建一个无限迭代器并对其进行过滤:

# Same as your function, but without the bugs
def gen_ip():
    return '.'.join(str(random.randrange(256)) for _ in range(4))

# Obviously not the real logic; that's left as an exercise to the reader of
# https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
def is_private_ip(ip):
    return not ip.startswith('2')

# Now this is an infinite iterator of non-private IP addresses.
ips = ifilterfalse(repeatfunc(gen_ip), is_private_ip)

现在您可以获得10个IP,如下所示:

>>> take(10, ips)
['205.150.11.90',
 '203.233.175.192',
 '211.241.64.223',
 '250.224.20.172',
 '203.26.103.176',
 '20.107.5.214',
 '204.181.205.180',
 '234.24.178.180',
 '22.225.212.59',
 '237.122.140.163']

我使用了来自recipes in the ^{} docstakerepeatfunc,以及来自itertools本身的ifilterfalse。你知道吗

更有效的解决方案是创建一个所有可能地址(或地址的一部分)的列表,在这个数组中生成索引,并根据这个索引选择元素。像这样:

bs = [0, 1, 2, 3, ..., 191, 193, ..., 255]
idx = random.randrange(0, len(ips), 1) 
b = bs[idx]
# or simpler: b = random.choice(bs)

相关问题 更多 >