Python: Performing Mathematical Functions between IP Address Octets
<p>I'm trying to perform the following:</p>

<pre><code>firstoctet * 256 + secondoctet = * 256 + thirdoctet = * 256 + fourthoctet = x
</code></pre>

<p>When I use this as an example :</p>

<pre><code>64.233.187.99 (google.com)
64 * 256 + 233 = * 256 + 187 = * 256 + 99 = http://1089059683/
</code></pre>

<p>Can someone please provide a method as to how this can be done? The mathematical sequence is no problem, i'm just unsure as to how I can take the octet values out of the decimal points to perform the math functions. </p>

<p>Thanks in advance!</p>

<p>If you're on Python 3.3 or higher, you can leverage <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow">the <code>ipaddress</code> module</a> to avoid reinventing the wheel, and it even provides a useful view as <code>bytes</code> that <code>int.from_bytes</code> can efficiently convert to a real <code>int</code>:</p>

<pre><code>from ipaddress import IPv4Address

ip_as_addr = IPv4Address("64.233.187.99")
ip_as_int = int.from_bytes(ip_as_addr.packed, 'big')
print(ip_as_int, hex(ip_as_int))
</code></pre>

<p>gets you output of <code>1089059683 0x40e9bb63</code>.</p>

<p>You could do this by hand if you really wanted to, I just like the self-documenting aspect of the above code. If Py 3.3+ isn't an option, you can get the same results with:</p>

<pre><code>octets = map(int, "64.233.187.99".split('.'))
ip_as_int = sum(octet &lt;&lt; ((3 - i) * 8) for i, octet in enumerate(octets))
</code></pre>

<p>That just splits the octets apart, converts them to <code>int</code>, then shifts each of them left by 24, 16, 8 and 0 bits (to align the octets properly), which then allows <code>sum</code> to combine them into a single <code>int</code>.</p>

python python-2.7 python-3.x