Any have any good code for converting a IPv6 address string into an integer? Converting IPv4 seems to be fairly easy, with the one format. However, IPv6 has several different formats to show an address:
- XXXX:XXXX:XXXX:XXXX::
- XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX
- XXXX:XXX:XXXX:0:0:XXXX:XXX:XXXX
- XXXX:XXX:XXXX::XXXX:XXX:XXXX
- ::ffff:XXXX:XXX (IPv4 in v6 format)
- ::ffff:###.#.#.### (also valid IPv4 in v6 format)
I'd like to be able to take one of these strings and translate it into an INTEGER for IP-to-network matching, and allow for any of these formats as the input.
Ended up rolling my own. Also realized that Oracle's 126-bit INTEGER is not enough bits for IPv6's 128-bit addresses. Frankly, I don't know how the original C library's INET6_ATON (or INET_PTON) does it, considering that I've never heard of a 16-byte integer.
I ended up with a 32-byte hex string, which means I have to do some fancy "half-string" math on nettohex and use SUBSTR for the FBIs to work correctly. (Blasted PL/SQL doesn't allow for "RETURN CHAR(32)"...)
Overall, though, it works well, works in all formats, and allows for index-based character comparisons to find out if an IP address is within an IP range.
Here's the full code:
UPDATE: Oracle 11g does allow for the SUBSTR entry to be put a virtual column. So, you could have columns like this:
And indexes like:
Using WHERE clauses like: