{"id":1287,"date":"2012-06-15T08:09:31","date_gmt":"2012-06-15T08:09:31","guid":{"rendered":"http:\/\/truelogic.org\/wordpress\/?p=1287"},"modified":"2012-06-15T08:09:31","modified_gmt":"2012-06-15T08:09:31","slug":"adding-ip-restriction-to-a-web-page-in-asp-net","status":"publish","type":"post","link":"https:\/\/truelogic.org\/wordpress\/2012\/06\/15\/adding-ip-restriction-to-a-web-page-in-asp-net\/","title":{"rendered":"Adding IP restriction to a web page in ASP.NET"},"content":{"rendered":"            <script type=\"text\/javascript\" src=\"https:\/\/truelogic.org\/wordpress\/wp-content\/plugins\/wordpress-code-snippet\/scripts\/shBrushCSharp.js\"><\/script>\n<p><a href=\"https:\/\/truelogic.org\/wordpress\/2012\/06\/15\/adding-ip-restriction-to-a-web-page-in-asp-net\/lock\/\" rel=\"attachment wp-att-1294\"><img loading=\"lazy\" decoding=\"async\" class=\"alignleft size-full wp-image-1294\" title=\"lock\" src=\"https:\/\/truelogic.org\/wordpress\/wp-content\/uploads\/2012\/06\/lock.jpeg\" alt=\"\" width=\"240\" height=\"160\" \/><\/a>In some cases , you may want to restrict access to a certain aspx page based on a restricted IP list. For instance, you way want admin reports to be accessed only from the head office or you may want a particular page to be accessible only from a certain location(s).<\/p>\n<p>This can be easily handled at the page level . The concept involves two things:<\/p>\n<ol>\n<li>Setup a file of valid IP ranges<\/li>\n<li>Query the file to check against the client IP to allow or disallow access<\/li>\n<\/ol>\n<p><strong>The IP list file<\/strong><\/p>\n<p>This is a simple ASCII text file in the format: <strong><em>start ip range-ending ip range<\/em><\/strong><\/p>\n<p>An example list would be<\/p>\n<p><em>10.255.128.20-10.255.128.36<\/em><br \/>\n<em>10.255.129.11-10.255.129.30<\/em><br \/>\n<em>10.255.130.11-10.255.130.22<\/em><br \/>\n<em>10.255.131.4-10.255.131.10<\/em><br \/>\n<em>10.255.132.1-10.255.132.10<\/em><br \/>\n<em>10.255.132.7-10.255.132.7<\/em><\/p>\n<p>This file can be edited manually offline since its unlikely that it will be edited very often,<\/p>\n<p><strong>THE IP CHECKING CODE<\/strong><\/p>\n<p>We define a class which will take in an IP address range and then validate a given IP against it. The calling code will open the ip list file and run the class against each of the ip ranges in the file. If it finds a match in any ip range, it will allow access to the page:<\/p>\n<p>The code for the class is given below:<br \/>\n<pre class=\"brush: csharp\">public class IPAddressRange\r\n{\r\n    private AddressFamily addressFamily;\r\n    private byte[] lowerBytes;\r\n    private byte[] upperBytes;\r\n\r\n    public IPAddressRange(IPAddress lower, IPAddress upper)\r\n    {\r\n        \/\/ Assert that lower.AddressFamily == upper.AddressFamily\r\n        this.addressFamily = lower.AddressFamily;\r\n        this.lowerBytes = lower.GetAddressBytes();\r\n        this.upperBytes = upper.GetAddressBytes();\r\n    }\r\n\r\n    public bool IsInRange(IPAddress address)\r\n    {\r\n        if (address.AddressFamily != addressFamily)\r\n        {\r\n            return false;\r\n        }\r\n\r\n        byte[] addressBytes = address.GetAddressBytes();\r\n\r\n        bool lowerBoundary = true, upperBoundary = true;\r\n\r\n        for (int i = 0; i &lt; this.lowerBytes.Length &amp;&amp;\r\n            (lowerBoundary || upperBoundary); i++)\r\n        {\r\n            if ((lowerBoundary &amp;&amp; addressBytes[i] &lt; lowerBytes[i]) ||\r\n                (upperBoundary &amp;&amp; addressBytes[i] &gt; upperBytes[i]))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            lowerBoundary &amp;= (addressBytes[i] == lowerBytes[i]);\r\n            upperBoundary &amp;= (addressBytes[i] == upperBytes[i]);\r\n        }\r\n\r\n        return true;\r\n    }\r\n}\r\n<\/pre><\/p>\n<p>The calling code is given below. Here its in the Page_Load event:<br \/>\n<pre class=\"brush: csharp\">    protected void Page_Load(object sender, EventArgs e)\r\n    {\r\n                \/\/ check for valid ip\r\n        if (!Page.IsPostBack)\r\n        {\r\n            bool allow = false;\r\n            string clientIP = Request.UserHostAddress;\r\n            string fileName = Server.MapPath(&quot;~&quot;) + &quot;\/validIPS.txt&quot;;\r\n            StreamReader rdr = new StreamReader(fileName);\r\n            string data = rdr.ReadToEnd();\r\n            rdr.Close();\r\n\r\n            data = data.Replace(&#039;\\r&#039;, &#039; &#039;);\r\n            string[] lines = data.Split(&#039;\\n&#039;);\r\n            for (int i = 0; i &lt; lines.Length; i++)\r\n            {\r\n                string[] range = lines[i].Split(&#039;-&#039;);\r\n                string lower = range[0].Trim();\r\n                string upper = range[1].Trim();\r\n                IPAddress ipLower = IPAddress.Parse(lower);\r\n                IPAddress ipUpper = IPAddress.Parse(upper);\r\n                IPAddressRange ipRange = new IPAddressRange(ipLower, ipUpper);\r\n                if (ipRange.IsInRange(IPAddress.Parse(clientIP)))\r\n                    allow = true;\r\n            }\r\n\r\n         \r\n            if (!allow)\r\n            {\r\n                Response.Write(&quot;You have been blocked due to IP restriction. Your IP is &quot; + clientIP);\r\n                Response.End();\r\n            }\r\n        }\r\n<\/pre><\/p>\n<p>Be sure to add<br \/>\n<em>using System.IO;<\/em><br \/>\n<em> using System.Net;<\/em><br \/>\n<em> using System.Net.Sockets;<\/em><\/p>\n<p>in the calling page<\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>In some cases , you may want to restrict access to a certain aspx page based on a restricted IP list. For instance, you way <a class=\"mh-excerpt-more\" href=\"https:\/\/truelogic.org\/wordpress\/2012\/06\/15\/adding-ip-restriction-to-a-web-page-in-asp-net\/\" title=\"Adding IP restriction to a web page in ASP.NET\">[&#8230;]<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":1294,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[17],"tags":[],"class_list":["post-1287","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-asp-net"],"_links":{"self":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1287","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/comments?post=1287"}],"version-history":[{"count":11,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1287\/revisions"}],"predecessor-version":[{"id":1299,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/1287\/revisions\/1299"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media\/1294"}],"wp:attachment":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media?parent=1287"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/categories?post=1287"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/tags?post=1287"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}