C 程式來驗證 IP 地址


在此程式中,我們將使用 C 驗證 IP 地址。IPv4 地址以點分十進位制表示。有四位十進位制數字(均在 0 到 255 之間)。這四個數字用三個點分隔。

有效 IP 的示例:192.168.4.1

要驗證 IP 地址,我們應遵循以下步驟

  • 使用句點“.”分隔符標記化字串(IP 地址)

  • 如果子字串包含任何非數字字元,則返回假

  • 如果每個標記中的數字不在 0 到 255 的範圍內,則返回假

  • 如果恰好有三個點和四個部分,那麼它是一個有效的 IP 地址

示例程式碼

#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
"): printf("Not valid
"); validate_ip(ip2)? printf("Valid
"): printf("Not valid
"); validate_ip(ip3)? printf("Valid
"): printf("Not valid
"); validate_ip(ip4)? printf("Valid
"): printf("Not valid
"); }

輸出

Valid
Valid
Not valid
Not valid

更新於:2019 年 7 月 30 日

7,000 多次瀏覽

職業生涯火速起步

完成這一課程,即可獲得認證

開始
廣告
© . All rights reserved.