Home » C++ programs » C++ Most popular & searched programs

C++ program to pad octets of IP Address with Zeros

Learn: How to pad IP Address octets with Zeros? In this C++ program, we will learn to pad each octet of an IP Address.

Sometimes, we need to use IP Address in three digits and we don’t want to input zeros with the digits, this C++ program will pad each octets of an IP Address with Zeros.

For Example: The Input format of an IP Address if "192.168.10.43", the output after padding with zeros will be "192.168.010.043".

Consider the program:



#include<iostream>
using namespace std;

#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 CIDR = 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);
}

//main program
int main()
{
	char ip[]="192.168.10.43";
	

	cout<<endl<<"IP  before padding:  "<<ip;

	padZeroIP(ip); 

	cout<<endl<<"IP  after padding:  "<<ip;
	cout<<endl;
	
	return 0;
}

Output

IP  before padding:  192.168.10.43
IP  after padding:  192.168.010.043

In above function we used strtok() function to tokenize IP address by dot (.) operator and then save each octets in 3 bytes padded with zeros.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.