Any valid IP address consists of four numbers separated by three period (.) characters and each number 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. Then use strcmp to further validate with reconstructed ip string.

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 != 0) && (n1 <= 255) && (n2 <= 255) && (n3 <= 255) && (n4 <= 255)) {
		char buf[64];
		sprintf(buf,"%u.%u.%u.%u",n1,n2,n3,n4);
		if(strcmp(buf,ip_str)) return 0;
		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
        0.123.234.12	INVALID
           1.255.4.5	VALID
        127.8.190.29	VALID
3hu23e832j2....wjdnw	INVALID
         3a.3b.2d.5t	INVALID
         -1.-1.-1.-1	INVALID
           1.1.1.1.3	INVALID
------------------------------------------

[neo@techpulp ~]#