判断IPV6地址格式是否正确

1.判断IPV6地址格式是否正确


此功能代码实现判断IPV6地址是否正确,正确返回1,错误误返回0。

#define  H(x)  ((unsigned char *) & (x) )[0]
#define  L(x)  ((unsigned char *) & (x) )[1]

//char * abbr, ipv6字符串
//unsigned char * ret_buff,返回和引用的buff
//return 传入buff的指针
int  CGlobalLogic::ipv6_to_u (char * abbr,unsigned char * ret_buff)
{
	char  buff[40]={0};
	int  ipv6_int[8]={0};
	int  two_colon = -1;
	int  ipv6_char_len = strlen(abbr);

	assert(abbr!=NULL && ret_buff!=NULL);
	//查找是否有缩写的情况
	//   two_colon=abbr.find_first_of("::");
	if((ipv6_char_len<3 )  
		||(abbr[0] ==':' && abbr[1]!=':') 
		||(abbr[ipv6_char_len-1]==':' && abbr[ipv6_char_len-2]!=':' ))
	{
		printf("Invalid ipv6 addr[%s]!",abbr);
		return 0;
	}

	for (int i=0;i='0'&&abbr[i]<='9')||(abbr[i]>='a'&&abbr[i]<='f')||(abbr[i]>='A'&&abbr[i]<='F')||abbr[i] == ':'))
		{
			printf("Invalid ipv6 addr[%s]!",abbr);
			return 0;
		}
	}
	for(int i=0,j=0;i4)
		{
			printf("Invalid ipv6 addr[%s], every 2Bytes not more than 4 chars!",abbr);
			return 0;
		}
	}

	//处理缩写的情况.
	if(two_colon>=0)
	{
		int pos = 0;
		int start_colon_num = 0;
		int end_colon_num = 0;
		int  add_colon_num = 0;
		//找:: 前面:的个数
		for(int i=0;i0)
		{
			buff[pos++] =':';
			add_colon_num --;
			if(add_colon_num!=0)
				buff[pos++] ='0';
		}
		for(int i=two_colon+2; i

你可能感兴趣的:(C++知识应用)