AI编程助手
AI免费问答

C程序验证IP地址的代码

WBOY   2023-09-04 21:13   1769浏览 转载

c程序验证ip地址的代码

在这个程序中,我们将看到如何使用C语言验证IP地址。IPv4地址以点十进制表示法表示。有四个十进制数(都在0到255之间)。这四个数字由三个点分隔。

一个有效的IP示例是:192.168.4.1

要验证IP地址,我们应该按照以下步骤进行:

  • 使用点“.”作为分隔符对字符串(IP地址)进行标记化

  • 如果子字符串包含任何非数字字符,则返回false

  • 如果每个标记中的数字不在0到255的范围内,则返回false

  • 如果有三个点和四个部分,则它是一个有效的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 <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>");
}</p></ctype.h></string.h></stdlib.h></stdio.h>

输出

Valid
Valid
Not valid
Not valid
声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除