识别有效的IP地址和掩码并进行分类统

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

int countA=0;
int countB=0;
int countC=0;
int countD=0;
int countE=0;
int countError=0;
int countPrivate=0;

void get(char *str)
{
    int num = strlen(str);

    int i=0;

    unsigned int arr[8] = {0};
    int counter = 0;

    int val = 0;
    for(i=0; i<=num; i++)
    {
        if(str[i]>='0' && str[i]<='9')
        {
            val = val*10 + str[i] - '0';
        }
        else if(str[i]=='.' || str[i]=='~'  || str[i]=='\0')
        {
            if(str[i-1]<'0' || str[i-1]>'9')
            {
                countError++;
                return;
            }
            if(val>255)
            {
                countError++;
                return;
            }
            if(counter>=8)
            {
                countError++;
                return;
            }
            arr[counter++] = val;
            val = 0;
        }
        else
        {
            return;
        }
    }


    unsigned int mask = (arr[4]<<24)+(arr[5]<<16)+(arr[6]<<8)+arr[7];

    int tmpi;
    for(tmpi=31; tmpi>=0 && (mask>>tmpi)%2==1; tmpi--);
    if(mask>>(tmpi+1)<<(tmpi+1) != mask)
    {
        countError++;
        return;
    }


    if(arr[0]>=1 && arr[0]<=126)
    {
        countA++;
    }

    if(arr[0]>=128 && arr[0]<=191)
    {
        countB++;
    }

    if(arr[0]>=192 && arr[0]<=223)
    {
        countC++;
    }

    if(arr[0]>=224 && arr[0]<=239)
    {
        countD++;
    }
    if(arr[0]>=240 && arr[0]<=255)
    {
        countE++;
    }

    if(arr[0]==10)
    {
        countPrivate++;
    }

    if(arr[0]==172 && (arr[1]>=16 && arr[1]<=31))
    {
        countPrivate++;
    }
    if(arr[0]==192 && arr[1]==168)
    {
        countPrivate++;
    }
}

int main()
{

    char str[100];

    while(cin>>str)
    {
        get(str);
    }

    cout<<countA<<' '<<countB<<' '<<countC<<' '<<countD<<' '<<countE<<' '<<countError<<' '<<countPrivate;

    return 0;
}

  

posted @ 2016-12-28 21:09  Hardsoftware  阅读(314)  评论(0编辑  收藏  举报