C code to check valid IP Address (IPv4) - Live Demo and ExampleC code to check valid IP Address (IPv4) - Live Demo and Example

Here is my sample source-code discussed in the video:

/* The Linux Channel
 * Code for Video Episode: 346 C code to check valid IP Address (IPv4)
 * Author: Kiran Kankipati
 * Updated: 15-Jun-2018
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>

static bool check_valid_ip_address(unsigned char *buf);

void main()
{	unsigned char buf[40];
	
	strcpy(buf, "192.168.0.1");

	if(check_valid_ip_address(buf)) { printf("Valid IPv4 Address: %s\n", buf); } else { printf("Invalid IPv4 Address: %s\n", buf); }
}


/*
IPv4 address - can be:
 - Host Address, Gateway
 - default route (0.0.0.0)
 - subnet mask
 - Network ID (network address, subnet)
*/
static bool check_valid_ip_address(unsigned char *buf)
{	char *pos = buf;
	
	
	if(buf==NULL) { return false; }
	
	//Dot count != 3 ??
	{	int dot_count = 0;	
		pos=buf; 
		while(*pos!='\0' && *pos!='\n')
		{	if(*pos=='.') { dot_count++; }
			pos++;
		}
		if(dot_count!=3) { return false; }
	}

	//Now parse octets and check the range
	{	char temp[10]; int temp_ptr = 0;
		int octet;
		
		pos = buf;
		while(*pos!='\0' && *pos!='\n')
		{	if((*pos)!='.')
			{	if(!isdigit(*pos)) { return false; }
			 	temp[temp_ptr] = *pos;
				temp_ptr++;
				temp[temp_ptr] = '\0'; 
			}
			else
			{	octet = (int) strtoul(temp, NULL, 10);
				//printf("octet: %d \n", octet);
				if(octet>=0 && octet<=255) { /* valid range */ } else { return false; }
				temp_ptr=0; temp[0]='\0';
			}
			pos++;
		}
		
		octet = (int) strtoul(temp, NULL, 10);
		//printf("octet: %d \n", octet);
		if(octet>=0 && octet<=255) { /* valid range */ } else { return false; }
	}
	
	return true; /* valid IPv4 addr */
}

you can compile the same via:

gcc -o check_valid_ipv4_addr check_valid_ipv4_addr.c