華爲面試題:識別有效的ip地址和子網掩碼並分類 C語言源碼

識別有效的ip地址和子網掩碼並分類:
按行輸入多組數據 
10.8.9.2~255.0.0.0
180.8.9.2~255.254.0.0
打印:A B C D E 錯誤的ip或掩碼 私有ip  的個數
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define MAX_PATH 256

int maze[10][10] = {0};
int route[100][2] = {0};

int impl(char *ip,char *mask,int *privateIp)
{
	char *a = strtok(ip,".");
	char *b = strtok(NULL,".");
	char *c = strtok(NULL,".");
	char *d = strtok(NULL,".");

	if (!(a && b && c && d))
	{
		return 5;
	}
	int ai = atoi(a);
	int bi = atoi(b);
	int ci = atoi(c);
	int di = atoi(d);
// 	char *a1 = strtok(mask,".");
// 	char *b1 = strtok(NULL,".");
// 	char *c1 = strtok(NULL,".");
// 	char *d1 = strtok(NULL,".");

	if(ai>0 && ai<=126 && strcmp(mask,"255.0.0.0")==0)
	{
		if (ai==10 && bi>=0 && bi<=255)
		{
			*privateIp = 1;
		}
		return 0;
	}
	else if(ai>=128 && ai<=191 && strcmp(mask,"255.255.0.0")==0)
	{
		if (ai==172 && bi>=16 && bi<=31)
		{
			*privateIp = 1;
		}
		return 1;
	}
	else if(ai>=192 && ai<=223 && strcmp(mask,"255.255.255.0")==0)
	{
		if (ai==192 && bi==168)
		{
			*privateIp = 1;
		}
		return 2;
	}
	else if(ai>=224 && ai<=239)
	{
		return 3;
	}
	else if(ai>=240 && ai<=255)
	{
		return 4;
	}
	else
	{
		return 5;
	}
}
int main()
{

// 	char test[4][100]={"10.70.44.68~255.254.255.0",
// 		"1.0.0.1~255.0.0.0",
// 		"192.168.0.2~255.255.255.0",
// 		"19..0.~255.255.255.0"};
	
	int result[7] = {0};
	char test[100] = {0};
	while(scanf("%s",test)!=EOF)
	{
		char *ip = strtok(test,"~");
		char *mask = strtok(NULL,"~");
		int n = impl(ip,mask,&result[6]);
		result[n]++;
	}
// 	for (int i=0;i<4;i++)
// 	{
// 		char *ip = strtok(test[i],"~");
// 		char *mask = strtok(NULL,"~");
// 		int n = impl(ip,mask,&result[6]);
// 		result[n]++;
// 	}
	for (int i=0;i<7;i++)
	{
		printf("%d ",result[i]);
	}
	return 0;
}


 

發佈了52 篇原創文章 · 獲贊 40 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章