You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#调用nmap扫描常用端口并解决自动关闭、多进程启动问题

问题原因及修复方案

双nmap进程问题

你代码中连续执行了两次nmap启动逻辑:

  • 第一次是实例化Process对象后调用.Start()方法启动nmap
  • 第二次是调用Process.Start()静态方法再次启动nmap
    两次调用都会生成独立的nmap.exe进程,删除任意一处启动逻辑即可解决该问题。

扫描完成自动关闭、无法查看结果问题

该问题有两个解决方案,可根据你的需求选择:

方案1:让nmap运行窗口停留,直接在控制台查看结果

通过cmd启动nmap,执行完扫描后追加pause命令让窗口不自动关闭,修复后代码如下:

private void button1_Click(object sender, EventArgs e)
{
    string IP = ip.Text;                     
    new Process
    {
        StartInfo =
        {
            UseShellExecute = false,
            FileName = "cmd.exe",
            Arguments = $"/c nmap.exe --top-ports 20 {IP} & pause"
        }
    }.Start();
}

方案2:将nmap扫描结果回读到C#程序中,可自行在界面展示

重定向nmap的输出流,扫描完成后读取结果赋值给你的界面控件即可,修复后代码如下:

private void button1_Click(object sender, EventArgs e)
{
    string IP = ip.Text;                     
    Process nmapProcess = new Process
    {
        StartInfo =
        {
            UseShellExecute = false,
            FileName = "nmap.exe",
            Arguments = $"--top-ports 20 {IP}",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        }
    };
    nmapProcess.Start();
    // 读取扫描输出与错误信息
    string scanResult = nmapProcess.StandardOutput.ReadToEnd();
    string errorInfo = nmapProcess.StandardError.ReadToEnd();
    nmapProcess.WaitForExit();
    
    // 示例:将结果展示到名为resultTxt的文本框中
    // resultTxt.Text = scanResult + errorInfo;
}

内容的提问来源于stack exchange,提问作者user17371397

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 13:54:05