Click here to Skip to main content
15,902,891 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
SQL
I am developing port scanning tool using c#.that successfully retrieve a list of all open ports.along with the incoming packet details.
But Now i want to block and allow any specific port. I have been looking for someone help to guide me,how to block ports in windows using c#.
Posted
Updated 22-Apr-17 8:22am

1 solution

Call a shell command (netsh.exe). Assuming you're using Vista or later, it will be along the lines of:-
C#
RunShellCommand(
    "netsh.exe",
    String.Format("advfirewall firewall add rule name=\"{0}\" dir=in action=block protocol={1} localport={2} profile={3}",
    "My rule name",
    "TCP",
    4567, // Port
    "Private", // Can be Private, Domain, Public or Any
    out stdout,
    out stderr);

Which uses this helper method:-
C#
private int RunShellCommand(string command, string parms, out string stdout, out string stderr, bool waitForCompletion = true)
{
    ProcessStartInfo psi = new ProcessStartInfo(command);
    psi.RedirectStandardInput = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.UseShellExecute = false;
    psi.WindowStyle = ProcessWindowStyle.Hidden;
    psi.CreateNoWindow = true;
    Process proc = Process.Start(psi);
    System.IO.StreamWriter sw = proc.StandardInput;
    System.IO.StreamReader sr = proc.StandardOutput;
    System.IO.StreamReader se = proc.StandardError;
    sw.WriteLine(parms);
    sw.Close();
    stdout = sr.ReadToEnd();
    stderr = se.ReadToEnd();
    if (waitForCompletion)
        proc.WaitForExit();
    return proc.ExitCode;
}


run "netsh advfirewall firewall add rule /?" in a command prompt for syntax.
 
Share this answer
 
v2
Comments
owais2012 12-Jan-15 8:07am    
Thank You Sir for giving me a way..This code have been worked good..now i can easily add and block any inbound traffic service by defining their rules using c#.but now i am facing to much problem while validating the defining rule because the same rule can be made more than once on the same port,same service name,same protocol.
Now i want some Exception on rules,more than one rule can not be made on same port.
Can you help us that how to validate firewall rules through C#...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900