判斷一個ip地址合法性(基礎c,不用庫函數)


#include <stdio.h>
int judge(char *strIp);
int main()
{
    char a[20];
    while(1)
    {
        scanf("%s", a);
        if(0 == judge(a))
        {
            printf("this is a correct ip\n");
        }
    }
}

int judge(char *strIp)
{
   if(NULL == strIp)
   {
      return -1;
   }
//IP must start with 0-9 if(*strIp > '9' || *strIp < '0') { return -1; } int num = 0; int dotNum = 0; do { if(*strIp >= '0' && *strIp <= '9') { num = 10 * num + *strIp - '0'; } else if(('.' == *strIp) || ('\0' == *strIp)) { //filter the string including '..' or ending with '.' if('.' == *(strIp - 1)) { return -1; } //filter the section number large than 255 or little than 0 if(num < 0 || num > 255) { return -1; } num = 0; //record the number of right dots if('.' == *strIp) { dotNum++; } } else { //Can't have chars excluding '0' - '9' and '.' return -1; } }while(*(strIp++)) if(3 == dotNum) { // ip is correct return 0; } else { //the string is too short for ip return -1; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM