Netstat专注于(查找端口)

Cot*_*emp 1 c# netstat

我最近试图执行以下行;

string strCmdText;
strCmdText = "netstat -np TCP | find " + quote + number + quote + "";
System.Diagnostics.Process.Start("netstat.exe", strCmdText);

Logs.Write("LISTEN_TO(" + Registry_val1.Text + ")", strCmdText);
Run Code Online (Sandbox Code Playgroud)

现在要做的基本上是找到所有包含“ 80”的TCP端口,并将它们显示在我的定制日志系统中,该系统将在我的文件夹中创建一个日志。

这个.txt中的LISTEN_TO(80)-{date_time} .txt应该包含命令发出的文本,但是我得到的只是时间。

我如上所述调试了此命令,不幸的是,我所知道的只是CMDtext设置正确,并且我的日志记录系统正常运行,让我别无选择,一旦启动查询,NETSTAT可能会关闭?

希望我提供了足够的信息,因为这是我的第一篇文章。

问候,

有限公司

由于描述不明确,这是我尝试执行的其他相同代码,但是仍然只能得到一些时间。

const string quote = "\"";
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.Arguments = "netstat -np TCP | find " + quote + number + quote + "";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();

String output = p.StandardOutput.ReadToEnd();

Logs.Write("LISTEN_TO(" + Registry_val1.Text + ")", output);
Run Code Online (Sandbox Code Playgroud)

基本上,您可以将其视为:textbox1.text =输出; execpt现在将输出放入日志文件。

ren*_*ene 6

我不明白为什么首先要使用netstat。.Net框架有许多提供各种数据的类,在这种情况下,IPGlobalProperties具有所需的方法。

var ip =  System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();

foreach(var tcp in ip.GetActiveTcpConnections()) // alternative: ip.GetActiveTcpListeners()
{
        if (tcp.LocalEndPoint.Port == number 
         || tcp.RemoteEndPoint.Port == number)
        {
           Logs.Write(
                String.Format(
                   "{0} : {1}", 
                   tcp.LocalEndPoint.Address, 
                   tcp.RemoteEndPoint.Address));
        }
}
Run Code Online (Sandbox Code Playgroud)

使用内置类的好处是易于调整和选择所需的内容,并且最重要的是:您可以为自己和用户节省进程外调用和输出解析。

  • 对已接受答案的一项更正:您应该使用“GetActiveTcpListeners()”查看活动侦听器,而不是查看“GetActiveTcpConnections()” (2认同)