Search code examples
cipdigits

Convert every part of IP number to three digit in C


My question is how to convert every part of IP number to three digits? For example 127.0.0.1 becomes 127.000.000.001

It is easy to do in languages like Python but I am new in C and do not know how to handle it.


Solution

  • char ip1[] = "127.0.0.1";
    
    int a1, a2, a3, a4;
    sscanf(ip1, "%i.%i.%i.%i", &a1, &a2, &a3, &a4);
    
    char ip2[16];
    snprintf(ip2, sizeof(ip2), "%03i.%03i.%03i.%03i", a1, a2, a3, a4);
    

    Forgot the zeros in the snprintf!