Check if an IP Address is within a given Subnet Mask in C# A simple helper method that can be used to check if a specific IP address is part of a given Subnet Mask using C#

If you're using a reverse proxy, a CDN such as Cloudflare, a third-party Wide Application Firewall, or any other intermediate caching and/or forwarding service to serve your website over the internet, you might want to ensure that the underlying web server (typically called "origin") is only accessible to the IP addresses of such service (the "edge"). Doing that is very important from an IT security perspective because it will prevent malicious attackers (assuming they manage to retrieve the origin server's IP  address) to bypass the edge proxy and directly connect to the origin server.

To know more about the edge-origin pattern and how to implement it, check out this post.
.

To comply with that using IIS, we're published several posts explaining how to set up the IP Addresses restriction built-in IIS feature using either the IIS Manager GUI or the web.config file. Such an approach is great most of the time, but what if you want to achieve the same outcome programmatically? More precisely, is there a way to check if a given IP address - let's say, the caller's IP address - is part of a given Subnet Mask in C#?

IsInSubnetMask helper method

As a matter of fact, the answer is YES! Here's a neat method that can be used to achieve such a result, compatible with IPv4 and IPv6 as long as we use CIDR notation (IPAddress/PrefixLength - example: 90.98.102.116/24).

The above method is strongly based on this StackOverflow answer by Christoph Sonntag: from what we have seen, it works perfectly! If you take a look at the original answer, you'll also find some useful XUnit tests.

Conclusions

That's it: we hope that the above helper method will help other C# and ASP.NET Core developers to check if a specific IP address is part of a given Subnet Mask.

 

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.