Thursday, July 26, 2012

Program to validate the given IPv4 address:)


#include
#include

int isValidIp (char *str)
{
    int segs = 0;
    int chcnt = 0;
    int accum = 0;

    if (str == NULL)
        return 0;
    while (*str != '\0')
    {
        if (*str == '.')
        {
            if (chcnt == 0)
                return 0;
            if (++segs == 4)
                return 0;
            chcnt = accum = 0;
            str++;
            continue;
        }
        if ((*str < '0') || (*str > '9'))
            return 0;
        if ((accum = accum * 10 + *str - '0') > 255)
            return 0;
        chcnt++;
        str++;

    }
    if (segs != 3)
        return 0;
    if (chcnt == 0)
        return 0;
    return 1;
}

int main()
{
    char strg[18];
    while(1)
    {
        printf("\n Enter IP : ");
        scanf("%s", strg);
        isValidIp(strg) ? printf("\n Valid IP") : printf("\n Invalid IP");
    }
    return 0;
}

No comments: