parsing ip adress string in 4 single bytes

BETSCH picture BETSCH · Feb 9, 2012 · Viewed 21.7k times · Source

I'm programming on a MCU with C and I need to parse a null-terminated string which contains an IP address into 4 single bytes. I made an example with C++:

#include <iostream>
int main()
{
    char *str = "192.168.0.1\0";
    while (*str != '\0')
    {
            if (*str == '.')
            {
                    *str++;
                    std::cout << std::endl;
            }
            std::cout << *str;
            *str++;
    }
    std::cout << std::endl;
    return 0;
}

This code prints 192, 168, 0 and 1 each byte in a new line. Now I need each byte in a single char, like char byte1, byte2, byte3 and byte4 where byte1 contains 1 and byte4 contains 192... or in a struct IP_ADDR and return that struct then, but I dont know how to do it in C. :(

Answer

pmg picture pmg · Feb 9, 2012

You can do it character-by-character, as does the C++ version in your question.

/* ERROR CHECKING MISSING */
#include <ctype.h>
#include <stdio.h>
int main(void) {
    char *str = "192.168.0.1", *str2;
    unsigned char value[4] = {0};
    size_t index = 0;

    str2 = str; /* save the pointer */
    while (*str) {
        if (isdigit((unsigned char)*str)) {
            value[index] *= 10;
            value[index] += *str - '0';
        } else {
            index++;
        }
        str++;
    }
    printf("values in \"%s\": %d %d %d %d\n", str2,
              value[0], value[1], value[2], value[3]);
    return 0;
}