#i"/> #i">

Home  >  Article  >  Backend Development  >  C program to verify IP address code

C program to verify IP address code

WBOY
WBOYforward
2023-09-04 21:13:101384browse

C program to verify IP address code

In this program we will see how to verify IP address using C language. IPv4 addresses are expressed in dotted decimal notation. There are four decimal numbers (all between 0 and 255). The four numbers are separated by three dots.

An example of a valid IP is: 192.168.4.1

To verify the IP address we should follow these steps:

  • Use dot ". ” as delimiter to tokenize a string (IP address)

  • Returns false if the substring contains any non-numeric characters

  • If the number in each tag is not in the range 0 to 255, return false

  • If there are three dots and four parts, it is a valid IP address

Sample code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int validate_number(char *str) {
   while (*str) {
      if(!isdigit(*str)){ //if the character is not a number, return
         false
         return 0;
      }
      str++; //point to next character
   }
   return 1;
}
int validate_ip(char *ip) { //check whether the IP is valid or not
   int i, num, dots = 0;
   char *ptr;
   if (ip == NULL)
      return 0;
      ptr = strtok(ip, "."); //cut the string using dor delimiter
      if (ptr == NULL)
         return 0;
   while (ptr) {
      if (!validate_number(ptr)) //check whether the sub string is
         holding only number or not
         return 0;
         num = atoi(ptr); //convert substring to number
         if (num >= 0 && num <= 255) {
            ptr = strtok(NULL, "."); //cut the next part of the string
            if (ptr != NULL)
               dots++; //increase the dot count
         } else
            return 0;
    }
    if (dots != 3) //if the number of dots are not 3, return false
       return 0;
      return 1;
}
int main() {
   char ip1[] = "192.168.4.1";
   char ip2[] = "172.16.253.1";
   char ip3[] = "192.800.100.1";
   char ip4[] = "125.512.100.abc";
   validate_ip(ip1)? printf("Valid</p><p>"): printf("Not valid</p><p>");
   validate_ip(ip2)? printf("Valid</p><p>"): printf("Not valid</p><p>");
   validate_ip(ip3)? printf("Valid</p><p>"): printf("Not valid</p><p>");
   validate_ip(ip4)? printf("Valid</p><p>"): printf("Not valid</p><p>");
}

Output

Valid
Valid
Not valid
Not valid

The above is the detailed content of C program to verify IP address code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete