Trying to write fast non dependency IP4 string validator for embedded system, It should counts leading zeros, values over 255 and other corrupted strings. Not sure if I missed something. Сan you guys take a look:
// Return 0 on error, store result to segs, if segs != 0.
int is_valid_ip4(const char *str, unsigned char* segs)
{
int dots = 0; // Dot count.
int chcnt = 0; // Character count within segment.
int accum = 0; // Accumulator for segment.
// Catch NULL pointer.
if (str == 0)
return 0;
// Process every character in string.
for (;;)
{
// Check numeric.
if (*str < '0' || *str > '9')
return 0;
// Prevent leading zeros.
if (chcnt > 0 && accum == 0)
return 0;
// Accumulate and check segment.
accum = accum * 10 + *str - '0';
if (accum > 255)
return 0;
// Store result.
if (segs)
segs[dots] = (unsigned char)accum;
// Advance other segment specific stuff.
++chcnt;
++str;
// Finish at the end of the string when 3 points are found.
if (*str == '\0' && dots == 3)
return 1;
// Segment changeover.
if (*str == '.')
{
// Limit number of segments.
++dots;
if (dots == 4)
return 0;
// Reset segment values.
chcnt = 0;
accum = 0;
++str;
}
}
}