[英]how to remove host from ip address?
Currently, I created a method to generate random ip(IPv4) address as below: 当前,我创建了一种生成随机ip(IPv4)地址的方法,如下所示:
def rand_ip(mask=False):
"""This uses the TEST-NET-3 range of reserved IP addresses.
"""
test_net_3 = '203.0.113.'
address = test_net_3 + six.text_type(random.randint(0, 255))
if mask:
address = '/'.join((address,
six.text_type(random.randrange(24, 32))))
return address
And now, I need enhance the method with the ability to remove host address when I had the mask enabled, the case is below 现在,我需要增强此方法,使其具有在启用掩码时删除主机地址的能力,具体情况如下
1.1.2.23/24(before) => 1.1.2.0/24(after host address removed)
1.1.2.23/16 => 1.1.0.0 (the same as above)
actually the change is just replace the left part(32-mask, right to left) with 0 in hexadecimal, Is there any simple way or existed libs can do this(python 2.7x and 3.x's compatibility should be considered)? 实际上,更改只是将十六进制的0替换为左部分(32-mask,从右到左),是否有任何简单的方法或存在的lib可以做到这一点(应考虑python 2.7x和3.x的兼容性)?
Is this something that you were looking for? 这是您要找的东西吗?
>>> from netaddr import *
>>> ip = IPNetwork('1.1.2.23/16')
>>> ip.ip
IPAddress('1.1.2.23')
>>> ip.network
(IPAddress('1.1.0.0')
>>> ip.netmask
(IPAddress('255.255.0.0')
To randomly generate an IP and netmask you can use this code. 要随机生成IP和网络掩码,可以使用此代码。 This can be done better though. 不过,这可以做得更好。
import random
def get_random_ip():
def ip():
return random.randint(0, 255)
value = str(ip())
for i in range(3):
value = value + "." + str(ip())
return value
def get_random_cidr():
return random.randrange(24, 32)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.