You can ban an IP by adding a rule on Windows Firewall via command prompt using this method:
void BanIP(string RuleName, string IPAddress, string Port, string Protocol)
{
if (!string.IsNullOrEmpty(RuleName) && !string.IsNullOrEmpty(IPAddress) && !string.IsNullOrEmpty(Port) && !string.IsNullOrEmpty(Protocol) && new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
{
using (Process RunCmd = new Process())
{
RunCmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
RunCmd.StartInfo.FileName = "cmd.exe";
RunCmd.StartInfo.Arguments = "/C netsh advfirewall firewall add rule name=\"" + RuleName + "\" dir=in action=block remoteip=" + IPAddress + " remoteport=" + Port + " protocol=" + Protocol;
RunCmd.Start();
}
}
}
Usage:
BanIP("Rule1", "151.21.1.1", "3389" "TCP") // Will ban the IP 151.21.1.1 (RDP).
BanIP("Rule2", "151.21.1.1", "Any" "TCP") // Will ban the IP 151.21.1.1 with any TCP ports.
BanIP("Rule3", "151.21.1.1", "3380-3390" "TCP") // Will ban the IP 151.21.1.1 with 3380-3390 TCP port range.
Note that this command will work starting with Windows Server 2012 R2 and that administrative privileges are required. Also remember that being a process external to your C# code, there is no guarantee that this will work, it is up to you to add checks to verify that everything is working correctly.