Home » Blog Posts » How to block IP addresses from accessing your ASPNET website

How to block IP addresses from accessing your ASPNET website

 Category:Web Design  
 By: usericon nonny01  

fblog
 Created: 3/11/2020 11:42:00 AM

Introduction

Block IP addresses

Due to spam comments from bots and malicious visitors, I decided to come up with a solution to prevent these users from accessing our website. I thought of several ways to go about blocking visitors. After some research, I came up with a technique whereby all comments/contributions to the website and the IP addresses of these users will be logged. Afterward, these comments are reviewed and the IP addresses of spammy contents blocked.

To block these users, we simply get their IP addresses using the code below:


C#

string ipadd;
ipadd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipadd == "" || ipaddress == null)
    ipadd = Request.ServerVariables["REMOTE_ADDR"];


VB.NET

Dim ipadd As String
ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If ipadd = "" Or ipaddress Is Nothing Then
   ipadd = Request.ServerVariables("REMOTE_ADDR")
End If




Then

We add the IP address to the web config file using the following code:



      <system.webServer>
      <security>
         <ipSecurity>
            <add ipAddress="192.169.102.1" />
            <add ipAddress="168.252.0.0" subnetMask="255.255.0.0" />
         </ipSecurity>
      </security>
   </system.webServer>

        
           
      


The first restriction denies access to the IP address 192.169.102.1, and the second restriction denies access to the entire 168.252.0.0 network.




Note: Blocking someone from accessing your website is not entirely possible. There are other strategies tech-savvy users can employ to access a website. But the approach taken above will make it harder for these users to access/contribute to your website.  


Leave your comment/question
You can use some HTML tags, such as <b>, <i>, <a>