如何判断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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值