1. 程式人生 > >如何判斷IP地址是否合法

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