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>Your code compares strings, not numbers. I would suggest using tuples instead:</p>

<pre><code>&gt;&gt;&gt; ip_range = [(1,1,0,0), (1,1,255,255)]
&gt;&gt;&gt; testip = (1,1,2,2)
&gt;&gt;&gt; testip &gt; ip_range[0] and testip &lt; ip_range[1]
True
&gt;&gt;&gt; testip = (1,3,1,1)
&gt;&gt;&gt; testip &gt; ip_range[0] and testip &lt; ip_range[1]
False
</code></pre>

python ip