如何判断IP地址是否合法

如何判断一个IP地址是否合法,以及如何判断一个IP地址是否在给定的IP地址范围内,废话不多说,上代码


判断IP地址是否合法:

bool isValidIP(char *ip)
{
	if (ip == NULL)
		return false;
	char temp[4];
	int count = 0;
	while (true)
	{
		int index = 0;
		while (*ip != '\0' && *ip != '.' && count < 4)
		{
			temp[index++] = *ip;
			ip++;
		}
		if (index == 4)
			return false;
		temp[index] = '\0';
		int num = atoi(temp);
		if (!(num >= 0 && num <= 255))
			return false;
		count++;
		if (*ip == '\0')
		{
			if (count == 4)
				return true;
			else
				return false;
		}
		else
			ip++;
	}
}




判断一个IP地址是否在给定的IP地址范围内:

bool IsIpInner(string strDesIp, string strBegin, string strEnd)
{
	char* tempDesIp = const_cast<char*>(strDesIp.c_str());
	char* tempBegin = const_cast<char*>(strBegin.c_str());
	char* tempEnd = const_cast<char*>(strEnd.c_str());
	if (isValidIP(tempDesIp) && isValidIP(tempBegin) && isValidIP(tempEnd))
	{
		unsigned long lDesIp = GetIpInt(strDesIp);
		unsigned long lBegin = GetIpInt(strBegin);;
		unsigned long lEnd = GetIpInt(strEnd);;
		return (((lDesIp >= lBegin) && (lDesIp <= lEnd)) || ((lDesIp <= lBegin) && (lDesIp >= lEnd)));
	}
	else
		return false;
}

其中GetIpInt(string strIp)是将IP地址转化为可比较大小的整形数,如下:

unsigned long GetIpInt(string strIp)
{
	char* tempIp = const_cast<char*>(strIp.c_str());
	char *next_token = NULL;
	char* ch1 = strtok_s(tempIp, ".", &next_token);
	char* ch2 = strtok_s(NULL, ".", &next_token);
	char* ch3 = strtok_s(NULL, ".", &next_token);
	char* ch4 = strtok_s(NULL, ".", &next_token);
	unsigned long a = stoi(ch1);
	unsigned long b = stoi(ch2);
	unsigned long c = stoi(ch3);
	unsigned long d = stoi(ch4);
	return a * 255 * 255 * 255 + b * 255 * 255 + c * 255 + d;
}


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页