Convert IPv6 address into string

This is code I used to convert IPv6 address into string before switching to WPP, the code only runs at PASSIVE_LEVEL:

// convert IPv6 address to string, RtlIpv6AddressToString is only available on vista+
// IRQL == PASSIVE_LEVEL
VOID util_address_to_string_v6(__in const PUINT8 paddr, __out_ecount(46) PWSTR S)
{
    UINT8 zero_pos = 0, zero_pos_max = 0;
    UINT8 zero_len = 0, zero_len_max = 0;
    UINT8 pos = 0, charsleft = 46, zeros_just_printed = 0;
    PWSTR p = S;
    for(pos = 0; pos < 16; ++pos)
    {
        if(0 == paddr[pos])
        {
            if(zero_len == 0)
            {
                zero_pos = pos;
                zero_len = 1;
            }
            else
            {
                zero_len = pos – zero_pos + 1;
            }
        }
        else
        {
            if(zero_len != 0)
            {
                if(zero_len > zero_len_max && zero_len >= 2)
                {
                    zero_pos_max = zero_pos;
                    zero_len_max = zero_len;
                }

                zero_pos = 0;
                zero_len = 0;
            }
        }
    }
    if(zero_len > zero_len_max && zero_len >= 2)
    {
        zero_pos_max = zero_pos;
        zero_len_max = zero_len;
    }
    pos = 0;
    while(pos < 16)
    {
        if(pos == zero_pos_max)
        {
            RtlStringCchPrintfW(p, charsleft, L”::”);
            p += 2;
            charsleft -= 2;
            pos += zero_len_max;

            zeros_just_printed = 1;
        }
        else
        {
            UINT8 charcount = (paddr[pos] > 0xF ? 2 : 1);
            if(pos > 0 && zeros_just_printed == 0)
            {
                RtlStringCchPrintfW(p, charsleft, L”:”);
                p += 1;
                charsleft -= 1;
            }
            RtlStringCchPrintfW(p, charsleft, L”%x”, paddr[pos]);
            p += charcount;
            charsleft -= charcount;
           
            zeros_just_printed = 0;
            ++pos;
        }
    }
}

Advertisements

Posted on April 11, 2011, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: