In: Computer Science
A valid IPv4 address is of the form ###.###.###.###, where each number, separated by '.', is 8 bits [0, 255]. Create program that validates input string containing an IP address. Use C programming language.
- Remove any newline \n from input string
- The input prompt should say "Enter IP Address of your choosing: "
- If IP address is invalid, it should print "You entered invalid IP\n"
- If IP address is valid, it should print "You entered valid IP\n"
- Convert string to integer using atof
Example:
• Valid IP
Enter IP Address of your choosing: 192.169.0.4
You entered valid IP
• Invalid IP
Enter IP Address of your choosing: 192.666.432.1122
You entered invalid IP
//Compiled using gcc compiler
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int validate_number(char *str) {
while (*str) {
if(!isdigit(*str)){ //if the
character is not a number, return false
return 0;
}
str++; //point to next
character
}
return 1;
}
int validateip(char *ip) { //check whether the IP is valid or
not
int i, num, dots = 0;
char *ptr;
if (ip == NULL)
return 0;
ptr = strtok(ip, "."); //cut the
string using dor delimiter
if (ptr == NULL)
return 0;
while (ptr) {
if (!validate_number(ptr)) //check
whether the sub string is holding only number or not
return 0;
num = atoi(ptr);
//convert substring to number
if (num >= 0
&& num <= 255) {
ptr = strtok(NULL, "."); //cut the next part of the string
if (ptr != NULL)
dots++; //increase the dot count
} else
return 0;
}
if (dots != 3) //if the number of dots are not
3, return false
return 0;
return 1;
}
int main() {
char ip[50],n;
printf("Enter the ip address:");
scanf("%s",ip);
n=validateip(ip);
if(n==1)
printf("You entered valid
IP\n");
else
printf("You entered invalid
IP\n");
}
OUTPUT