I have seen solutions written online in C, but I want a C++ way to pad an IPv4 address with zeroes.
C code found online
using namespace std;
#include<iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void padZeroIP(char *str)
{
int oct1=0;
int oct2=0;
int oct3=0;
int oct4=0;
int i = 0;
const char s[2] = ".";
char *token;
/* get the first token */
token = strtok(str, s);
oct1 = atoi(token);
/* walk through other tokens */
while( token != NULL )
{
token = strtok(NULL, s);
if(i==0)
oct2 = atoi(token);
else if(i==1)
oct3 = atoi(token);
else if(i==2)
oct4 = atoi(token);
i++;
}
sprintf(str,"%03d.%03d.%03d.%03d",oct1,oct2,oct3,oct4);
}
Once again, with feeling:
std::string padZeroIP(const std::string& str)
{
using boost::asio::ip::address_v4;
auto ip = address_v4::from_string(str).to_bytes();
std::string result(16, '\0');
std::snprintf(result.data(), result.size(), //
"%03d.%03d.%03d.%03d", //
ip[0], ip[1], ip[2], ip[3]);
result.resize(15);
return result;
}
This doesn't assume input is valid and doesn't reinvent the wheel. See it Live On Coliru:
127.0.0.1 -> 127.000.000.001
1.1.1.1 -> 001.001.001.001
OVERKILL
Keep in mind that IPv4 addresses can take many forms, E.g. 127.1
is valid for 127.0.0.1
.
So is 0177.1
or 0x7f.1