Q:

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

0

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

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to set network settings for IPv6 Netwo... >>
<< C++ program to set MAC address in Linux Devices...