首页 > 后端开发 > C++ > 正文

C程序验证IP地址的代码

WBOY
发布: 2023-09-04 21:13:10
转载
1879人浏览过

c程序验证ip地址的代码

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

一个有效的IP示例是:192.168.4.1

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

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

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

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

    代码小浣熊
    代码小浣熊

    代码小浣熊是基于商汤大语言模型的软件智能研发助手,覆盖软件需求分析、架构设计、代码编写、软件测试等环节

    代码小浣熊 51
    查看详情 代码小浣熊
  • 如果有三个点和四个部分,则它是一个有效的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</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>");
}
登录后复制

输出

Valid
Valid
Not valid
Not valid
登录后复制

以上就是C程序验证IP地址的代码的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号