阻止函数生成私有地址

时间:2013-06-10 23:50:50

标签: 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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

# 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 itertools docstakerepeatfunc以及来自ifilterfalse本身的itertools

答案 2 :(得分:-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)