// Experiment 8: Check if a given IPv4 address is valid or not
// Compile: gcc 08_ipv4_validate.c -o ipv4check
// Run    : ./ipv4check

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

// Returns 1 if valid, 0 otherwise
int isValidIPv4(const char *ip) {
    if (ip == NULL) return 0;

    int num, dots = 0;
    char buf[64];
    if (strlen(ip) >= sizeof(buf)) return 0;
    strcpy(buf, ip);

    // strtok cannot detect leading/trailing dots or empty fields,
    // so check manually first
    if (buf[0] == '.' || buf[strlen(buf)-1] == '.') return 0;

    char *token = strtok(buf, ".");
    while (token != NULL) {
        // Each token must be 1-3 digits, all numeric
        int len = strlen(token);
        if (len < 1 || len > 3) return 0;
        for (int i = 0; i < len; i++)
            if (!isdigit(token[i])) return 0;

        num = atoi(token);
        if (num < 0 || num > 255) return 0;

        // Disallow leading zeros (e.g., "01")
        if (token[0] == '0' && len > 1) return 0;

        dots++;
        token = strtok(NULL, ".");
    }

    return (dots == 4) ? 1 : 0;
}

int main() {
    char ip[64];
    printf("Enter an IPv4 address: ");
    if (scanf("%63s", ip) != 1) return 1;

    if (isValidIPv4(ip))
        printf("%s is a VALID IPv4 address.\n", ip);
    else
        printf("%s is NOT a valid IPv4 address.\n", ip);

    return 0;
}
