C program to check string is valid IPv4 address or not
Write a C program to check given string is valid IPv4 address or not.This program will read an IP address in String and check whether it is a valid IPv4 address or not.
According to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1
STEPS : :
Following are steps to check whether a given string is valid IPv4 address or not:
step 1)
Parse string with “.” as delimiter using “strtok()” function.
e.g. ptr =
strtok
(str, DELIM);
step 2)
……..a) If ptr contains any character which is not digit then return 0
……..b) Convert “ptr” to decimal number say ‘NUM’
……..c) If NUM is not in range of 0-255 return 0
……..d) If NUM is in range of 0-255 and ptr is non-NULL increment “dot_counter” by 1
……..e) if ptr is NULL goto step 3 else goto step 1step 3)
if dot_counter != 3 return 0 else return 1.
Below is the source code of the C program to check given string is valid IPv4 address or not which is successfully compiled and run on the windows system.The Output of the program is shown below.
SOURCE : :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
#include <stdio.h> #include <string.h> #include <stdlib.h> #define DELIM "." /* return 1 if string contain only digits, else return 0 */ int valid_digit(char *ip_str) { while (*ip_str) { if (*ip_str >= '0' && *ip_str <= '9') ++ip_str; else return 0; } return 1; } /* return 1 if IP string is valid, else return 0 */ int is_valid_ip(char *ip_str) { int i, num, dots = 0; char *ptr; if (ip_str == NULL) return 0; ptr = strtok(ip_str, DELIM); if (ptr == NULL) return 0; while (ptr) { /* after parsing string, it must contain only digits */ if (!valid_digit(ptr)) return 0; num = atoi(ptr); /* check for valid IP */ if (num >= 0 && num <= 255) { /* parse remaining string */ ptr = strtok(NULL, DELIM); if (ptr != NULL) ++dots; } else return 0; } /* valid IP string must contain 3 dots */ if (dots != 3) return 0; return 1; } // Driver program to test above functions int main() { char ip1[] = "128.0.0.251"; char ip2[] = "128.16.100.1"; char ip3[] = "128.512.100.1"; char ip4[] = "125.512.200.cde"; is_valid_ip(ip1)? printf("Valid\n"): printf("Not valid\n"); is_valid_ip(ip2)? printf("Valid\n"): printf("Not valid\n"); is_valid_ip(ip3)? printf("Valid\n"): printf("Not valid\n"); is_valid_ip(ip4)? printf("Valid\n"): printf("Not valid\n"); return 0; } |
Also Read : : Write a C program to check date is valid or not
OUTPUT : :
1 2 3 4 |
Valid Valid Not valid Not valid |