How to block or unblock IP address in IIS programatically using .Net

In my earlier post How to get list of applications in IIS programatically using .Net, I discussed how to automate IIS management using managed API. One of the common task or action that lot of applications perform is block or unblock IP addresses of users that may be violating some rules or trying to attack your site. Here is code sample that will answer following questions.

  • How to block an IP addreess in IIS using .Net?
  • How to unblock an IP address in IIS using .Net?
static void BlockIpAddress(string site, string ip)
{
   var serverManager = new ServerManager();
   var hostConfig = serverManager.GetApplicationHostConfiguration();
   // Get ipSecurity section in configuration.
   var ipSecuritySection = hostConfig.GetSection("system.webServer/security/ipSecurity", site);
   var configElements = ipSecuritySection.GetCollection();
   // Check if this ip address is already blocked.
   var ipExists = false;
   foreach (var elem in configElements)
   {
     if (elem.ElementTagName == "add")
     {
        var ipaddr = elem.Attributes["ipAddress"];
        if (null == ipaddr)
        {
           continue;
        }
        if (ipaddr.Value == ip)
        {
          // Check value of "allowed" attribute.
          if ((bool)elem.Attributes["allowed"].Value == true)
          {
           // Simple change this attribute to false and we are done.
           elem.Attributes["allowed"].Value = false;
           break;
          }
        }
      }
    }
    if (!ipExists)
    {
       // Create new element and add it to collection.
       var newElement = configElements.CreateElement("add");
       newElement.Attributes["ipAddress"].Value = ip;
       newElement.Attributes["allowed"].Value = false;
       configElements.Add(newElement);
    }

    serverManager.CommitChanges();
 }

Search

Social

Weather

18.0 °C / 64.3 °F

weather conditions Clear

Monthly Posts

Blog Tags