Advertisement
MdSadmanSiraj

ip_validate.c

Jul 19th, 2022
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5. int validate_number(char *str) {
  6.    while (*str) {
  7.       if(!isdigit(*str)){ //if the character is not a number, return
  8.          false
  9.          return 0;
  10.       }
  11.       str++; //point to next character
  12.    }
  13.    return 1;
  14. }
  15. int validate_ip(char *ip) { //check whether the IP is valid or not
  16.    int i, num, dots = 0;
  17.    char *ptr;
  18.    if (ip == NULL)
  19.       return 0;
  20.       ptr = strtok(ip, "."); //cut the string using dor delimiter
  21.       if (ptr == NULL)
  22.          return 0;
  23.    while (ptr) {
  24.       if (!validate_number(ptr)) //check whether the sub string is
  25.          holding only number or not
  26.          return 0;
  27.          num = atoi(ptr); //convert substring to number
  28.          if (num >= 0 && num <= 255) {
  29.             ptr = strtok(NULL, "."); //cut the next part of the string
  30.             if (ptr != NULL)
  31.                dots++; //increase the dot count
  32.          } else
  33.             return 0;
  34.     }
  35.     if (dots != 3) //if the number of dots are not 3, return false
  36.        return 0;
  37.       return 1;
  38. }
  39. int main() {
  40.    char ip1[] = "192.168.4.1";
  41.    char ip2[] = "172.16.253.1";
  42.    char ip3[] = "192.800.100.1";
  43.    char ip4[] = "125.512.100.abc";
  44.    validate_ip(ip1)? printf("Valid\n"): printf("Not valid\n");
  45.    validate_ip(ip2)? printf("Valid\n"): printf("Not valid\n");
  46.    validate_ip(ip3)? printf("Valid\n"): printf("Not valid\n");
  47.    validate_ip(ip4)? printf("Valid\n"): printf("Not valid\n");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement