Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
GreenGeeks Web Hosting - Faster, Scalable & Eco-Friendly

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


8,090 questions

11,268 answers

573 users

How to check if a string is valid IPv4 (IP) address in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
#define DELIMITER "."
 
int is_only_digits(char *ip)
{
    while (*ip) {
        if (*ip >= '0' && *ip <= '9')
            ip++;
        else
            return 0;
    }
    return 1;
}
 
int is_valid_IPv4(char *ip)
{
    int n, dots = 0;
    char *p;
 
    if (ip == NULL)
        return 0;
 
    p = strtok(ip, DELIMITER);
    if (p == NULL)
        return 0;
 
    while (p) {
        if (!is_only_digits(p))
            return 0;
 
        n = atoi(p);
 
        if (n >= 0 && n <= 255) {
            p = strtok(NULL, DELIMITER);
            if (p != NULL)
                dots++;
        } else
            return 0;
    }
 
    if (dots == 3)
        return 1;
        
    return 0;
}
 
int main()
{
    char ip1[] = "127.0.0.1";
    char ip2[] = "172.16.251.1";
    char ip3[] = "85.98.555.1";
    char ip4[] = "255.255.255.a";
    char ip5[] = "255.255.255.0.0";
    
    printf("%s ", ip1); is_valid_IPv4(ip1) ? printf("Valid\n") : printf("Not valid\n");
    printf("%s ", ip2); is_valid_IPv4(ip2) ? printf("Valid\n") : printf("Not valid\n");
    printf("%s ", ip3); is_valid_IPv4(ip3) ? printf("Valid\n") : printf("Not valid\n");
    printf("%s ", ip4); is_valid_IPv4(ip4) ? printf("Valid\n") : printf("Not valid\n");
    printf("%s ", ip5); is_valid_IPv4(ip5) ? printf("Valid\n") : printf("Not valid\n");
    
    return 0;
}

/*
run:

127.0.0.1 Valid
172.16.251.1 Valid
85.98.555.1 Not valid
255.255.255.a Not valid
255.255.255.0.0 Not valid

*/


 




answered May 15 by avibootz
edited May 15 by avibootz
...