Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,877 questions

51,801 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, 2018 by avibootz
edited May 15, 2018 by avibootz

Related questions

1 answer 184 views
2 answers 212 views
1 answer 193 views
193 views asked Apr 8, 2021 by avibootz
1 answer 149 views
1 answer 178 views
4 answers 205 views
205 views asked May 15, 2024 by avibootz
1 answer 174 views
174 views asked May 6, 2021 by avibootz
...