how to remove host from ip address?
<p>Currently, I created a method to generate random ip(IPv4) address as below:</p>

<pre><code>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
</code></pre>

<p>And now, I need enhance the method with the ability to remove host address when
I had the mask enabled, the case is below</p>

<pre><code>1.1.2.23/24(before) =&gt; 1.1.2.0/24(after host address removed) 
1.1.2.23/16 =&gt; 1.1.0.0 (the same as above)
</code></pre>

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

<p>Is this something that you were looking for?</p>

<pre><code>&gt;&gt;&gt; from netaddr import *
&gt;&gt;&gt; ip = IPNetwork('1.1.2.23/16')
&gt;&gt;&gt; ip.ip
IPAddress('1.1.2.23')
&gt;&gt;&gt; ip.network
(IPAddress('1.1.0.0')
&gt;&gt;&gt; ip.netmask
(IPAddress('255.255.0.0')
</code></pre>

<p>To randomly generate an IP and netmask you can use this code. This can be done better though. </p>

<pre><code>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)
</code></pre>

python ip openstack