/* Sample code from Techpulp.
 * You are free to use this source code as you wish.
 * However Techpulp provides no warranty that this code works ans claims no responsibility for any damage.
 * Author: neo@techpulp.com
 * http://www.techpulp.com/
 */
#include <stdio.h>
#include <unistd.h>

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;
}


char *test_ips[] = {
	"1.1.1.1",
	"255.255.255.255",
	"0.123.234.12",
	"1.255.4.5",
	"127.8.190.29",
	"3hu23e832j2....wjdnw",
	"3a.3b.2d.5t",
	"-1.-1.-1.-1",
	"1.1.1.1.3",
	NULL
};


int main(int argc, char *argv[])
{
	int i = 0;

	printf("\n------------------------------------------\n");
	printf("IP Address Validation\n");
	printf("------------------------------------------\n");
	while(test_ips[i]) {
		printf("%20s\t%s\n",
			test_ips[i],
			is_valid_ip(test_ips[i])?"VALID ":"INVALID "
			 );
		i++;
	}
	printf("------------------------------------------\n\n");

	return 0;
}

