[ipv6-ops] A postgresql & php inet to ip6.arpa snippet

Aaron Hughes aaronh at bind.com
Tue Jul 26 02:22:05 CEST 2011


Thanks Martin.

This is far more complicated, but php is so common. Just set the "39" to adjust for prefix length return in that $ORIGIN will likely be the /48. In this case 1.0.0.0.0.e.a.f.7.0.6.2.ip6.arpa.

Input: 2607:fae0:1:1:219:e3ff:fefa:927
Output: 7.2.9.0.a.f.e.f.f.f.3.e.9.1.2.0.1.0.0.0


function inet6_expand($addr)
{
    /* Check if there are segments missing, insert if necessary */
    if (strpos($addr, '::') !== false) {
        $part = explode('::', $addr);
        $part[0] = explode(':', $part[0]);
        $part[1] = explode(':', $part[1]);
        $missing = array();
        for ($i = 0; $i < (8 - (count($part[0]) + count($part[1]))); $i++)
            array_push($missing, '0000');
        $missing = array_merge($part[0], $missing);
        $part = array_merge($missing, $part[1]);
    } else {
        $part = explode(":", $addr);
    } // if .. else
    /* Pad each segment until it has 4 digits */
    foreach ($part as &$p) {
        while (strlen($p) < 4) $p = '0' . $p;
    } // foreach
    unset($p);
    /* Join segments */
    $result = implode(':', $part);
    /* Quick check to make sure the length is as expected */
    if (strlen($result) == 39) {
        return $result;
    } else {
        return false;
    } 
} 


Cheers,
Aaron


On Tue, Jul 26, 2011 at 02:10:47AM +0200, Martin Millnert wrote:
> 128-bit friends,
> 
> I just took the time to come up with a IMHO quite clean way to create
> ip6.arpa strings from inet types in PostgreSQL and thought I'd share (if
> nothing else so for the Internet archives, where I came up empty with a
> similar solution previously):
> 
> Prerequisites: a string reverse() function. Either, wait for/install 9.2
> where it seems to be included, or simply install for example this one:
> http://archives.postgresql.org/pgsql-sql/2005-02/msg00334.php
> 
> Then:
> sysdb=# SELECT
> reverse(regexp_replace(substring(encode(inet_send('2a02:9a0:100:2::101'::inet), 'hex') from 9), '(.)', E'.\\1', 'g'));
>                              reverse                              
> ------------------------------------------------------------------
>  1.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.0.0.1.0.0.a.9.0.2.0.a.2.
> (1 row)
> 
> It may not look as much, but for me the dark magic was the inet_send
> function to access the raw data of the inet type. I'm using this myself
> now to generate part of a zone file anyway.
> 
> Cheers,
> Martin
> 
> (If you're not using pgsql already, "you're doing it wrong" ;-) )

-- 

Aaron Hughes 
aaronh at bind.com
+1-831-824-4161
Key fingerprint = AD 67 37 60 7D 73 C5 B7 33 18 3F 36 C3 1C C6 B8
http://www.bind.com/



More information about the ipv6-ops mailing list