Hello There, Guest!
View New Posts  |  View Today's Posts
[C] IPv6 Reverse Zone calculation

  • 0 Vote(s) - 0 Average


12-08-2016, 09:51 PM #1
AceInfinity
Developer
*******
Administrators
Posts: 9,733 Threads:1,026 Joined: Jun 2011 Reputation: 76

IPv6 Reverse Zone calculation
IPv6 Reverse Zone calculation example I wrote in C just today:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <assert.h>

#define UNUSED(x) (void)(x)
#define BIT_COUNT(x) (sizeof(x) * CHAR_BIT)
#define BIT_MASK(x)  ((1 << x) - 1)
#define UBOUND(l) ((l) - 1)

#define IPV6_FIELD_COUNT 8
#define IPV6_FIELD_WIDTH 16

void ipv6_reverse_zone(char *ipv6)
{
    size_t n   = 0;
    long int l = 0;
    char *offset = ipv6;
    uint16_t fields[IPV6_FIELD_COUNT] = { 0 };

    do
    {
        if (*offset == ':') { ++offset; break; }
        l = strtol(offset, &offset, 16);
        /* assert(l != 0); */
        fields[n] = l & 0xffff; /* store 16-bits */
    }
    while (++n < IPV6_FIELD_COUNT && *offset++ == ':');

    if (*offset == '/')
    {
        l = strtol(offset + 1, NULL, 10);
        assert(l > 0 && l <= 128);
        if (l % 4 != 0) l = (l + 4) & -4; /* round CIDR to nearest nibble-boundary */
        do
        {
            --l;
            printf("%x.", (fields[l / IPV6_FIELD_WIDTH] >> (UBOUND(IPV6_FIELD_WIDTH)
                           - (l % IPV6_FIELD_WIDTH))) & UBOUND(IPV6_FIELD_WIDTH));
        }
        while ((l -= 3) > 0);
        puts("ip6.arpa");
    }
}

int main(void)
{
    ipv6_reverse_zone("2a06:1280:2000::/64");
    ipv6_reverse_zone("2a06:1280:2000::/1");
    ipv6_reverse_zone("2001:db8::/29");
    ipv6_reverse_zone("2a06:1280:2000::/128");
    ipv6_reverse_zone("2a06:1280:2000::/8");
    return 0;
}


Microsoft MVP .NET Programming - (2012 - Present)
®Crestron DMC-T Certified Automation Programmer

Development Site: aceinfinity.net

 ▲
 ▲ ▲




Forum Jump:


Possibly Related Threads...
Thread Author Replies Views Last Post
   Weissman Score Calculation AceInfinity 0 866 01-29-2015, 07:41 PM
Last Post: AceInfinity
   CodeJam Problem - 2010 (Problem B. Reverse Words) AceInfinity 5 3,807 11-12-2014, 02:33 AM
Last Post: Mazzn


Users browsing this thread: 1 Guest(s)