SoFunction
Updated on 2025-03-01

How to use C# to verify whether the IP is a LAN address

A while ago, a customer from [Guangzhou .NET Group] asked this question and said that they needed to verify whether the website entered by the customer was a LAN. In fact, there is no definite definition of the IP of the LAN. As long as it is in the LAN, it can be set as any IP.

But there is indeed a definition of an intranet reserved address, which will ensure that the address of the public IPv4 is not assigned to the "intranet reserved address", which is defined as follows:

10.0.0.0/8, i.e. 10.0.0.0-10.255.255.255;
172.16.0.0/12, that is, 172.16.0.0-172.31.255.255;
192.168.0.0/16, that is, 192.168.0.0-192.168.255.255.

The customer clarified that he really wanted to verify whether the IPv4 string is a reserved address for the intranet.

Let’s think of several ways to verify whether the IPv4 address string is a reserved address for the intranet.

First write out the signature of the method:

bool IsPrivateNetwork(string ipv4Address)
{
}

Then build the test data and display the expected results:

var testData = new Dictionary<string, bool>
{
	[""] = false, 
	["Not A IP"] = false, 
	["225.5.5.5"] = false,
	["175.10.74.64"] = false,
	["192.168.1.13"] = true,
	["10.10.24.220"] = true, 
	["172.24.1.120"] = true, 
	["172.32.1.120"] = false, 
};

string output = ("\r\n",
	(x => $"[{,12}] Expected: {,5},\tActual: {IsPrivateNetwork(),5}"));
	
(output);

Method 1 - StartsWith()

This is the easiest way to think of, using Substring, StartsWith and other methods of strings to implement:

bool IsPrivateNetwork(string ipv4Address)
{
	if ((ipv4Address, out _))
	{
		if (("192.168.") || ("10."))
		{
			return true;
		}

		if (("172."))
		{
			string seg2 = ipv4Address[4..7];
			if (('.') &&
				(seg2, "16.") >= 0 &&
				(seg2, "31.") <= 0)
			{
				return true;
			}
		}
	}

	return false;
}

Note that this method is very simple when verifying Class A website and Class C website (it does apply these two to most customers). Class B network is a special case, which makes this code slightly complicated and requires a few more strings to be judged - resulting in more complex code.

The input results are as follows:

[            ] Expected: False,  Actual: False
[    Not A IP] Expected: False,  Actual: False
[   225.5.5.5] Expected: False,  Actual: False
[175.10.74.64] Expected: False,  Actual: False
[192.168.1.13] Expected:  True,  Actual:  True
[10.10.24.220] Expected:  True,  Actual:  True
[172.24.1.120] Expected:  True,  Actual:  True
[172.32.1.120] Expected: False,  Actual: False

I think this method...is pretty good. The key is that it is very straightforward API calls, which are easy to understand. If I were the technical person in charge, I would mostly allow employees to write this way.

In addition, if you pursue "functional style", you may be able to write it like this and implement "one line of code" to complete it (the effect is the same):

bool IsPrivateNetwork2(string ipv4Address) => (ipv4Address, out _) && (
	("192.168.") ||
	("10.") ||
	("172.") && ipv4Address[6] == '.' && (ipv4Address[4..6]) switch
	{
		var x when x >= 16 && x <= 31 => true, 
		_ => false
	}
);

Method 2 - Use IPAddress

.NET is a treasure house. In addition to using IPAddress class to assist in verification, it will be much easier to implement:

bool IsPrivateNetwork3(string ipv4Address)
{
	if ((ipv4Address, out var ip))
	{
		byte[] ipBytes = ();
		if (ipBytes[0] == 10) return true;
		if (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31) return true;
		if (ipBytes[0] == 192 && ipBytes[1] == 168) return true;
	}

	return false;
}

The key to this method is to use the GetAddressBytes() method of the IPAddress class to fully verify this very easily - and the code is simpler.

If you pursue "functional" programming, the version of "one line" code is as follows (the effect is the same):

bool IsPrivateNetwork(string ipv4Address) => (ipv4Address, out var ip) && () switch 
{
	var x when x[0] == 10 => true, 
	var x when x[0] == 172 && x[1] >= 16 && x[1] <= 31 => true, 
	var x when x[0] == 192 && x[1] == 168 => true, 
	_ => false
};

Method 3 - Use regular expressions

This is quite troublesome, but there is nothing to say. Just enter the code:

bool IsPrivateNetwork(string ipv4Address) => (input, @"(^192\.168\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\.([1][6-9]|[2][0-9]|[3][0-1])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)", );

This is the real line of code

No kidding, the performance of regular expressions is actually much worse, far worse than the above two methods - the most important thing is that if I write this regular expression out, I will never want to maintain it again😂

Summarize

As the saying goes, "All roads lead to Rome." There may be different ways to complete a simple task, but there are still big differences between methods. I think the key is to write more, compare more, and experience more.

The above is the detailed content of how to use C# to verify whether an IP is a LAN address. For more information about C# to verify whether an IP is a LAN, please pay attention to my other related articles!