How to validate IP address in C
In Category C/C++ Networking
Any valid IP address consists of four numbers separated by three period (.) characters and each nunber ranges from 0-255 inclusive. An example IP address is “125.231.167.234″. The string function sscanf can be used to extract the four numbers and then validate each number for the range 0-255.
The following function returns 0 if the IP address is invalid and 1 if valid.
int is_valid_ip(const char *ip_str)
{
unsigned int n1,n2,n3,n4;
if(sscanf(ip_str,"%u.%u.%u.%u", &n1, &n2, &n3, &n4) != 4) return 0;
if((n1 <= 255) && (n2 <= 255) && (n3 <= 255) && (n4 <= 255)) return 1;
return 0;
}
Download: validate-ip.c
The output will be as follows if the code in validate-ip.c is executed.
[neo@techpulp ~]# gcc validate-ip.c -Wall -o validate-ip
[neo@techpulp ~]# ./validate-ip
------------------------------------------
IP Address Validation
------------------------------------------
1.1.1.1 VALID
255.255.255.255 VALID
1.255.4.5 VALID
127.8.190.29 VALID
3hu23e832j2....wjdnw INVALID
3a.3b.2d.5t INVALID
-1.-1.-1.-1 INVALID
------------------------------------------
[neo@techpulp ~]#
Recent Comments