Task: Parse an IP Address

C: #include <string.h>
#include <memory.h>


static unsigned int _parseDecimal ( const char** pchCursor )
{
    unsigned int nVal = 0;
    char chNow;
    while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
    {
        
        nVal *= 10;
        nVal += chNow - '0';

        ++*pchCursor;
    }
    return nVal;
}



static unsigned int _parseHex ( const char** pchCursor )
{
    unsigned int nVal = 0;
    char chNow;
    while ( chNow = **pchCursor & 0x5f, 
            (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || 
            (chNow >= 'A' && chNow <= 'F') 
            )
    {
        unsigned char nybbleValue;
        chNow -= 0x10;  
        nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
        
        nVal <<= 4;
        nVal += nybbleValue;

        ++*pchCursor;
    }
    return nVal;
}














int ParseIPv4OrIPv6 ( const char** ppszText, 
        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
    unsigned char* abyAddrLocal;
    unsigned char abyDummyAddr[16];

    
    const char* pchColon = strchr ( *ppszText, ':' );
    const char* pchDot = strchr ( *ppszText, '.' );
    const char* pchOpenBracket = strchr ( *ppszText, '[' );
    const char* pchCloseBracket = NULL;


    
    
    
    int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
            ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
    
    if ( bIsIPv6local )
    {
        
        pchCloseBracket = strchr ( *ppszText, ']' );
        if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
                pchCloseBracket < pchOpenBracket ) )
            return 0;
    }
    else    
    {
        
        if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
            return 0;
    }

    
    if ( NULL != pbIsIPv6 )
        *pbIsIPv6 = bIsIPv6local;
    
    
    
    
    abyAddrLocal = abyAddr; 
    if ( NULL == abyAddrLocal ) 
        abyAddrLocal = abyDummyAddr;

    
    
    
    if ( ! bIsIPv6local )   
    {
        
        
        
        unsigned char* pbyAddrCursor = abyAddrLocal;
        unsigned int nVal;
        const char* pszTextBefore = *ppszText;
        nVal =_parseDecimal ( ppszText );           
        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )    
            return 0;
        *(pbyAddrCursor++) = (unsigned char) nVal;  
        ++(*ppszText);  

        pszTextBefore = *ppszText;
        nVal =_parseDecimal ( ppszText );           
        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
            return 0;
        *(pbyAddrCursor++) = (unsigned char) nVal;
        ++(*ppszText);  

        pszTextBefore = *ppszText;
        nVal =_parseDecimal ( ppszText );           
        if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
            return 0;
        *(pbyAddrCursor++) = (unsigned char) nVal;
        ++(*ppszText);  

        pszTextBefore = *ppszText;
        nVal =_parseDecimal ( ppszText );           
        if ( nVal > 255 || pszTextBefore == *ppszText ) 
            return 0;
        *(pbyAddrCursor++) = (unsigned char) nVal;

        if ( ':' == **ppszText && NULL != pnPort )  
        {
            unsigned short usPortNetwork;   
            ++(*ppszText);  
            pszTextBefore = *ppszText;
            nVal =_parseDecimal ( ppszText );
            if ( nVal > 65535 || pszTextBefore == *ppszText )
                return 0;
            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
            *pnPort = usPortNetwork;
            return 1;
        }
        else    
        {
            if ( NULL != pnPort )
                *pnPort = 0;    
            return 1;
        }
    }
    else    
    {
        unsigned char* pbyAddrCursor;
        unsigned char* pbyZerosLoc;
        int bIPv4Detected;
        int nIdx;
        
        
        
        
        
        if ( NULL != pchOpenBracket )   
            *ppszText = pchOpenBracket + 1;
        pbyAddrCursor = abyAddrLocal;
        pbyZerosLoc = NULL; 
        bIPv4Detected = 0;
        for ( nIdx = 0; nIdx < 8; ++nIdx )  
        {
            const char* pszTextBefore = *ppszText;
            unsigned nVal =_parseHex ( ppszText );      
            if ( pszTextBefore == *ppszText )   
            {
                if ( NULL != pbyZerosLoc )  
                {
                    
                    if ( pbyZerosLoc == pbyAddrCursor )
                    {
                        --nIdx;
                        break;
                    }
                    return 0;   
                }
                if ( ':' != **ppszText )    
                    return 0;
                if ( 0 == nIdx )    
                {
                    ++(*ppszText);
                    if ( ':' != **ppszText )
                        return 0;
                }

                pbyZerosLoc = pbyAddrCursor;
                ++(*ppszText);
            }
            else
            {
                if ( '.' == **ppszText )    
                {
                    
                    const char* pszTextlocal = pszTextBefore;   
                    unsigned char abyAddrlocal[16];
                    int bIsIPv6local;
                    int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
                    *ppszText = pszTextlocal;   
                    if ( ! bParseResultlocal || bIsIPv6local )  
                        return 0;
                    
                    *(pbyAddrCursor++) = abyAddrlocal[0];
                    *(pbyAddrCursor++) = abyAddrlocal[1];
                    *(pbyAddrCursor++) = abyAddrlocal[2];
                    *(pbyAddrCursor++) = abyAddrlocal[3];
                    ++nIdx; 
                    bIPv4Detected = 1;  
                    break;  
                }

                if ( nVal > 65535 ) 
                    return 0;
                *(pbyAddrCursor++) = nVal >> 8;     
                *(pbyAddrCursor++) = nVal & 0xff;
                if ( ':' == **ppszText )    
                {
                    ++(*ppszText);
                }
                else    
                {
                    break;
                }
            }
        }
        
        
        if ( NULL != pbyZerosLoc )
        {
            int nHead = (int)( pbyZerosLoc - abyAddrLocal );    
            int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); 
            int nZeros = 16 - nTail - nHead;        
            memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );    
            memset ( pbyZerosLoc, 0, nZeros );      
        }
        
        
        if ( bIPv4Detected )
        {
            static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
            if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
                return 0;
        }

        
        if ( NULL != pchOpenBracket )
        {
            if ( ']' != **ppszText )
                return 0;
            ++(*ppszText);
        }

        if ( ':' == **ppszText && NULL != pnPort )  
        {
            const char* pszTextBefore;
            unsigned int nVal;
            unsigned short usPortNetwork;   
            ++(*ppszText);  
            pszTextBefore = *ppszText;
            pszTextBefore = *ppszText;
            nVal =_parseDecimal ( ppszText );
            if ( nVal > 65535 || pszTextBefore == *ppszText )
                return 0;
            ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
            ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
            *pnPort = usPortNetwork;
            return 1;
        }
        else    
        {
            if ( NULL != pnPort )
                *pnPort = 0;    
            return 1;
        }
    }

}



int ParseIPv4OrIPv6_2 ( const char* pszText, 
        unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
    const char* pszTextLocal = pszText;
    return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}








VB: Function parse_ip(addr)
    
    Set ipv4_pattern = New RegExp
    ipv4_pattern.Global = True
    ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}"
    
    Set ipv6_pattern = New RegExp
    ipv6_pattern.Global = True
    ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}"
    
    If ipv4_pattern.Test(addr) Then
        port = Split(addr,":")
        octet = Split(port(0),".")
        ipv4_hex = ""
        For i = 0 To UBound(octet)
            If octet(i) <= 255 And octet(i) >= 0 Then
                ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2)
            Else
                ipv4_hex = "Erroneous Address"
                Exit For
            End If 
        Next
        parse_ip = "Test Case: " & addr & vbCrLf &_
                   "Address: " & ipv4_hex & vbCrLf
        If UBound(port) = 1 Then
            If port(1) <= 65535 And port(1) >= 0 Then
                parse_ip = parse_ip & "Port: " & port(1) & vbCrLf
            Else
                parse_ip = parse_ip & "Port: Invalid" & vbCrLf
            End If
        End If
    End If
    
    If ipv6_pattern.Test(addr) Then
        parse_ip = "Test Case: " & addr & vbCrLf
        port_v6 = "Port: "
        ipv6_hex = ""
        
        If InStr(1,addr,"[") Then
            
            port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1)))
            
            addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1))
        End If
        word = Split(addr,":")
        word_count = 0
        For i = 0 To UBound(word)
            If word(i) = "" Then
                If i < UBound(word) Then
                    If Int((7-(i+1))/2) = 1 Then
                        k = 1
                    ElseIf UBound(word) < 6 Then
                        k = Int((7-(i+1))/2)
                    ElseIf UBound(word) >= 6 Then
                        k = Int((7-(i+1))/2)-1
                    End If
                    For j = 0 To k
                        ipv6_hex = ipv6_hex & "0000"
                        word_count = word_count + 1
                    Next
                Else
                    For j = 0 To (7-word_count)
                        ipv6_hex = ipv6_hex & "0000"
                    Next
                End If
            Else
                ipv6_hex = ipv6_hex & Right("0000" & word(i),4)
                word_count = word_count + 1
            End If
        Next
        parse_ip = parse_ip & "Address: " & ipv6_hex &_
                vbCrLf & port_v6 & vbCrLf
    End If
    
    If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then
        parse_ip = "Test Case: " & addr & vbCrLf &_
                   "Address: Invalid Address" & vbCrLf
    End If
End Function


ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_
    "[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode")

For n = 0 To UBound(ip_arr)
    WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf
Next