简体   繁体   中英

how to remove host from ip address?

Currently, I created a method to generate random ip(IPv4) address as below:

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)?

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM