【问题标题】:c++ What process is listening on a certain port in windowsc ++什么进程正在侦听Windows中的某个端口
【发布时间】:2010-10-28 08:24:10
【问题描述】:

我在 Visual c++ 中创建了一个程序,并在其中实现了一个 Web 服务。 Web 服务设置为监听 80 端口,但如果其他程序已在使用此端口,则 Web 服务无法启动。

所以当webservice无法启动时,我想要一个函数或方法,它可以获取当前使用80端口的进程名称。然后我可以向用户打印一个错误,并询问他关闭进程。

【问题讨论】:

    标签: c++ windows visual-c++ networking


    【解决方案1】:

    GetExtendedTcpTableGetExtendedUdpTable 为您提供网络连接列表。您可以浏览此列表并检查程序是否使用端口 80(它也提供进程 ID)。

    【讨论】:

    • 谢谢。 GetExtendedTcpTable 函数有点难以使用,因为微软的实现中应该存在一些错误,但在这个站点的帮助下,我得到了它的工作:mychinaworks.com/blog/lshen/2008/04/16/220
    【解决方案2】:

    我有一个在 C++ 中使用 Qt 的解决方案:

    /**
     * \brief Find id of the process that is listening to given port.
     * \param port A port number to which a process is listening.
     * \return The found process id, or 0 if not found.
     */
    uint findProcessListeningToPort(uint port)
    {
       QString netstatOutput;
       {
          QProcess process;
          process.start("netstat -ano -p tcp");
          process.waitForFinished();
          netstatOutput = process.readAllStandardOutput();
       }
       QRegularExpression processFinder;
       {
          const auto pattern = QStringLiteral(R"(TCP[^:]+:%1.+LISTENING\s+(\d+))").arg(port);
          processFinder.setPattern(pattern);
       }
       const auto processInfo = processFinder.match(netstatOutput);
       if (processInfo.hasMatch())
       {
          const auto processId = processInfo.captured(1).toUInt();
          return processId;
       }
       return 0;
    }
    

    【讨论】:

      【解决方案3】:

      作为第一次尝试,我会考虑将netstat 作为外部进程运行并捕获/解析输出。它为您提供活动连接。

      【讨论】:

      • 它测试了这个方法,“netstat -noa”也可以完成这项工作,但我需要将输出传输到一个文件,然后在我的程序中解析它。 GetExtendedTcpTable 为我提供了一个包含所有信息的 c++ 数组。
      【解决方案4】:

      不确定是否有办法通过 API(不是 Windows 程序员)执行此操作,但是您可以尝试将 netstat -abo 作为 shell 命令,然后在结果字符串中查找 TCP 和端口 80,然后您将具有二进制名称...

      编辑:我相信您至少需要 XP SP2 才能使其正常工作...

      【讨论】:

        猜你喜欢
        • 2010-09-10
        • 2012-06-15
        • 2010-09-08
        • 1970-01-01
        • 2015-03-18
        • 1970-01-01
        • 2016-03-19
        • 1970-01-01
        相关资源
        最近更新 更多