如何使用c#阻止和允许任何特定端口 [英] how to Block and Allow any specific port using c#

查看:426
本文介绍了如何使用c#阻止和允许任何特定端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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#.

推荐答案

调用shell命令(netsh.exe)。假设您使用的是Vista或更高版本,它将符合以下条件: -

Call a shell command (netsh.exe). Assuming you're using Vista or later, it will be along the lines of:-
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:-

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;
}





运行netsh advfirewall防火墙添加规则/?在语法的命令提示符中。



run "netsh advfirewall firewall add rule /?" in a command prompt for syntax.


这篇关于如何使用c#阻止和允许任何特定端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆