check if an IP is within a range of CIDR in Python
<p>I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is a dupe of my question) and is in another language.</p>

<p>I have a way to convert the subnet into the beginning and the end of the range of ip's in a subnet (okay, bad wording, it's simply like<code>1.1.1.1/16 -&gt; (1.1.0.0 , 1.1.255.255)</code>)</p>

<p>I now want to check if <code>1.1.2.2</code> is within this subnet. Can I simply do a <code>&gt;</code> and <code>&lt;</code> to compare?</p>

<pre><code>ip_range = ('1.1.0.0', '1.1.255.255')
if '1.1.2.2' &gt;= ip_range[0] and '1.1.2.2' &lt;= ip_range[1]:
     return True
</code></pre>

<p>When I tested it, it works, but I don't know if it would always work for any ipv4 ip's. I'd assume I'm just comparing ASCII order , so this should always work, but is there any exception?</p>

<p>You can't really do string comparisons on a dot separated list of numbers because your test will simply fail on input say <code>1.1.99.99</code> as <code>'9'</code> is simply greater than <code>'2'</code></p>

<pre><code>&gt;&gt;&gt; '1.1.99.99' &lt; '1.1.255.255'
False
</code></pre>

<p>So instead you can convert the input into tuples of integers through comprehension expression</p>

<pre><code>def convert_ipv4(ip):
    return tuple(int(n) for n in ip.split('.'))
</code></pre>

<p>Note the lack of type checking, but if your input is a proper IP address it will be fine.  Since you have a 2-tuple of IP addresses, you can create a function that takes both start and end as argument, pass that tuple in through argument list, and return that with just one statement (as Python allows chaining of comparisons).  Perhaps like:</p>

<pre><code>def check_ipv4_in(addr, start, end):
    return convert_ipv4(start) &lt; convert_ipv4(addr) &lt; convert_ipv4(end)
</code></pre>

<p>Test it out.</p>

<pre><code>&gt;&gt;&gt; ip_range = ('1.1.0.0', '1.1.255.255')
&gt;&gt;&gt; check_ipv4_in('1.1.99.99', *ip_range)
True
</code></pre>

<p>With this method you can lazily expand it to IPv6, though the conversion to and from hex (instead of int) will be needed instead.</p>

python ip