0

我如何防止这个 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
4

3 回答 3

1
def isPrivateIp (ip):
    # fill this
    return True or False

ip = gen_ip()
while isPrivateIp(ip):
    ip = gen_ip()
于 2013-06-10T23:52:50.730 回答
0

我认为poke的答案很棒。但是,如果您要在循环中生成和使用它们,我只需创建一个无限迭代器并对其进行过滤:

# 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']

我已经使用takeand repeatfuncfrom the recipes in the itertoolsdocsifilterfalsefromitertools本身。

于 2013-06-11T00:41:17.177 回答
-1

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

bs = [0, 1, 2, 3, ..., 191, 193, ..., 255]
idx = random.randrange(0, len(ips), 1) 
b = bs[idx]
# or simpler: b = random.choice(bs)
于 2013-06-11T00:01:37.567 回答