How to pad octets of IP Address with Zeros in C++

In this article, we are going to see how we can output an IP address with 3 digits for each part in C++. We can also say that we will pad octets of IP Address with Zeros in C++.

So, what is an IP address?

IP address is a label that is assigned to all the connected devices in a network. An IP address is used to host devices or for identification and location addressing.

Padding octets of IP Address with zeroes in C++

The requirement for this is due to the fact that, sometimes we need an IP address with 3 digits. But the IP address string that the computer receives might not have 3 digits for each part.

For eg: A typical IP address looks like 192.168.1.1. In this address, there are parts with a 3-bit address as well as a 1-bit address. To pad the IP with zeroes, we get the final result as: 192.168.001.001.

So, how do we reach this result? Let us write a C++ program to do so.

We define a simple function to perform the task by taking in the IP string. We also initialize some variables with 0.

#include<bits/stdc++.h>
using namespace std;
void change(char *str)
{
  int a1=0,a2=0,a3=0,a4=0;
  int c = 0;
  int i = 0;

We then use the C++ inbuilt functions- strtok(), atoi(), sprintf() to regulate our codes.

The strtok breaks the string into a series of tokens. atoi converts string into integer. And sprintf acts as a pointer to a string.

  const char s[2] = ".";
  char *t;
    	t = strtok(str, s);
  a1 = atoi(t);

    	while( t != NULL ) 
    	{
      t = strtok(NULL, s);
      
      if(i==0)
        a2 = atoi(t);
      else if(i==1)
        a3 = atoi(t);
      else if(i==2)
        a4 = atoi(t);
      i++;
    	}
    
    	sprintf(str,"%03d.%03d.%03d.%03d",a1,a2,a3,a4);
}

Finally, it’s time to declare the main function.

int main()
{
  char address[]="192.168.1.1";
  cout<<endl<<"IP address before padding=  "<<address;
  change(address); 

  cout<<endl<<"IP address after padding=  "<<address;
  cout<<endl;
  
  return 0;
}

We then get the padded IP address.

IP address before padding=  192.168.1.1
IP addressafter padding=  192.168.001.001

--------------------------------
Process exited after 2.975 seconds with return value 0
Press any key to continue . . .


This was all for the code. I hope this was of your help.

Also read: std::to_address in C++ with example

Leave a Reply

Your email address will not be published. Required fields are marked *