验证:给定的字符串是否IPv4或IPv6?

有时候,总想验证一些奇怪的想法,干脆就写下来,以备后查。

想法:验证给定的字符串是否IPv4或IPv6?

// 判断IPv4和IPv6地址
BOOL IsValidIpAddr(LPCTSTR ipAddr, BOOL *ipv4, BOOL *loop)
{
	BOOL result = FALSE;
	IN_ADDR addr4 = {0};
	IN6_ADDR addr6 = {0};

	if (1 == InetPton(AF_INET, ipAddr, &addr4))
	{
		result = TRUE;

		if (ipv4 != NULL)
		{
			*ipv4 = TRUE;
		}

		if (loop != NULL)
		{
			// 127.0.0.1
			if (addr4.s_addr == 0x0100007F)
			{
				*loop = TRUE;
			}
			else
			{
				*loop = FALSE;
			}
		}
	}
	else if (1 == InetPton(AF_INET6, ipAddr, &addr6))
	{
		result = TRUE;

		if (ipv4 != NULL)
		{
			*ipv4 = FALSE;
		}

		if (loop != NULL)
		{
			// ::1
			DWORD dw1 = *(DWORD*)&addr6.u.Byte[0];
			DWORD dw2 = *(DWORD*)&addr6.u.Byte[4];
			DWORD dw3 = *(DWORD*)&addr6.u.Byte[8];
			DWORD dw4 = *(DWORD*)&addr6.u.Byte[12];
			if (dw1 == 0 && dw2 == 0 && dw3 == 0 && dw4 == 0x01000000)
			{
				*loop = TRUE;
			}
			else
			{
				*loop = FALSE;
			}
		}
	}

	return result;
}

 

// 测试IPv4和IPv6地址的判断
void TestCase_IsValidIpAddr()
{
	LPCTSTR ipAddr[] = {
		_T("1.2.3.4"),
		_T("0.0.0.0"),
		_T("127.0.0.1"),
		_T("123.456.789.012"),
		_T("255.255.255.255"),
		_T("ABCD:EF01:2345:6789:ABCD:EF01:2345:6789"),
		_T("ABCD:EF:1:2:3:4:5:6789"),
		_T("ABCD:EF::15:6789"),
		_T("ABCD:EF01:2345:6789:ABCD:EF01:192.168.1.1"),
		_T("::1"),
		NULL,
		_T(""),
		_T("this is a string.")
	};

	for (unsigned int i = 0; i < _countof(ipAddr); i++)
	{
		BOOL ipv4, loop;

		if (! IsValidIpAddr(ipAddr[i], &ipv4, &loop))
		{
			_tprintf_s(_T("invalid IP address. [%s] \n"), ipAddr[i]);
		}
		else
		{
			_tprintf_s(_T("valid IP address. [%s] [%u] [%u] \n"), ipAddr[i], ipv4, loop);
		}
	}
}

 

执行结果:

Visual Leak Detector Version 2.5.1 installed.
valid IP address. [1.2.3.4] [1] [0]
valid IP address. [0.0.0.0] [1] [0]
valid IP address. [127.0.0.1] [1] [1]
invalid IP address. [123.456.789.012]
valid IP address. [255.255.255.255] [1] [0]
valid IP address. [ABCD:EF01:2345:6789:ABCD:EF01:2345:6789] [0] [0]
valid IP address. [ABCD:EF:1:2:3:4:5:6789] [0] [0]
valid IP address. [ABCD:EF::15:6789] [0] [0]
valid IP address. [ABCD:EF01:2345:6789:ABCD:EF01:192.168.1.1] [0] [0]
valid IP address. [::1] [0] [1]
invalid IP address. [(null)]
invalid IP address. []
invalid IP address. [this is a string.]
No memory leaks detected.

 

你可能感兴趣的:(C/C++VC++)