• C语言检查ip是否合法


    在工作当中我们经常会遇到这种问题:判断一个输入的字符串是否为合法的IP地址,下面是一个测试小程序:

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <stdlib.h>
     4 #include <stdbool.h>
     5 
     6 bool isVaildIp(const char *ip)
     7 {
     8     int dots = 0; /*字符.的个数*/
     9     int setions = 0; /*ip每一部分总和(0-255)*/ 
    10 
    11     if (NULL == ip || *ip == '.') { /*排除输入参数为NULL, 或者一个字符为'.'的字符串*/ 
    12         return false;
    13     }   
    14 
    15     while (*ip) {
    16 
    17         if (*ip == '.') {
    18             dots ++; 
    19             if (setions >= 0 && setions <= 255) { /*检查ip是否合法*/
    20                 setions = 0;
    21                 ip++;
    22                 continue;
    23             }   
    24             return false;
    25         }   
    26         else if (*ip >= '0' && *ip <= '9') { /*判断是不是数字*/
    27             setions = setions * 10 + (*ip - '0'); /*求每一段总和*/
    28         } else 
    29             return false;
    30         ip++;   
    31     }   
    32    /*判断IP最后一段是否合法*/ 
    33     if (setions >= 0 && setions <= 255) {
    34         if (dots == 3) {
    35             return true;
    36         }   
    37     }   
    38 
    39     return false;
    40 }
    41 
    42 void help()
    43 {
    44     printf("Usage: ./test <ip str>
    ");
    45     exit(0);
    46 }
    47 
    48 int main(int argc, char **argv)
    49 {
    50     if (argc != 2) {
    51         help(); 
    52     }   
    53 
    54     if (isVaildIp(argv[1])) {
    55         printf("Is Vaild Ip-->[%s]
    ", argv[1]);
    56     } else {
    57         printf("Is Invalid Ip-->[%s]
    ", argv[1]);
    58     }   
    59 
    60     return 0;
    61 }

    运行结果:

    1 [root@localhost isvildip]# ./test 192.168.1.1
    2 Is Vaild Ip-->[192.168.1.1]
    3 [root@localhost isvildip]# ./test 192.168.1.256
    4 Is Invalid Ip-->[192.168.1.256]
    5 [root@localhost isvildip]# 
  • 相关阅读:
    P1182 数列分段 Section II 题解
    P3853 路标设置题解
    二分模板
    P2678 跳石头题解
    P2440 木材加工题解
    P1024 一元三次方程求解题解
    快速下载vscode的方法
    P1824 进击的奶牛题解
    P1873 砍树题解
    用户登录之asp.net cookie的写入、读取与操作
  • 原文地址:https://www.cnblogs.com/wenqiang/p/5959835.html
Copyright © 2020-2023  润新知