In this article, we are going to learn how to validate an IP address if it is a valid IP address. The IP address is normally 4 octal numbers with dots. Each octal number is within the range of 0 to 255. It should not be outside this range.
C Program to validate an IP address
In this example, we are taking the IP strings, and then we will tokenize this string with dots as delimiters. Then each token should be a number with a range of 0 to 255. If this check pass it means this is a valid IP, if this check is not passed it means it is an Invalid IP address. Also, we will validate that each token is a number and not a string or character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int ValidateIP(char *ipaddr);
int validate_number(char *octat) ;
int main()
{
char ipaddr1[] = "192.168.126.2";
char ipaddr2[] = "182.14.253.10";
char ipaddr3[] = "922.800.100.20";
char ipaddr4[] = "125.xyz.100.abc";
if(ValidateIP(ipaddr1))
printf("The IP address \"192.168.126.2\" is Valid.\n");
else
printf("The IP address \"192.168.126.2\" is Invalid.\n");
if(ValidateIP(ipaddr2))
printf("The IP address \"182.14.253.10\" is Valid.\n");
else
printf("The IP address \"182.14.253.10\" is Invalid.\n");
if(ValidateIP(ipaddr3))
printf("The IP address \"922.800.100.20\" is Valid.\n");
else
printf("The IP address \"922.800.100.20\" is Invalid.\n");
if(ValidateIP(ipaddr4))
printf("The IP address \"125.xyz.100.abc\" is Valid.\n");
else
printf("The IP address \"125.xyz.100.abc\" is Invalid.\n");
}
//In this function we are checking if the passed string is a number or not
int validate_number(char *octat)
{
while (*octat)
{
if(!isdigit(*octat))
{
return 0;
}
octat++;
}
return 1;
}
//In this function we are checking if the passed string is a number within the range of valid IP ( 0-255)
int ValidateIP(char *ipaddr)
{
int i, num, dots = 0;
char *ptr;
if (ipaddr == NULL)
return 0;
// tokenise the string in to each octat Number
ptr = strtok(ipaddr, ".");
if (ptr == NULL)
return 0;
while (ptr)
{
if (!validate_number(ptr))
return 0;
num = atoi(ptr);
if (num >= 0 && num <= 255)
{
ptr = strtok(NULL, ".");
if (ptr != NULL)
dots++;
}
else
return 0;
}
if (dots != 3)
return 0;
return 1;
}
Output
The IP address "192.168.126.2" is Valid.
The IP address "182.14.253.10" is Valid.
The IP address "922.800.100.20" is Invalid.
The IP address "125.xyz.100.abc" is Invalid.