【发布时间】:2010-10-28 08:24:10
【问题描述】:
我在 Visual c++ 中创建了一个程序,并在其中实现了一个 Web 服务。 Web 服务设置为监听 80 端口,但如果其他程序已在使用此端口,则 Web 服务无法启动。
所以当webservice无法启动时,我想要一个函数或方法,它可以获取当前使用80端口的进程名称。然后我可以向用户打印一个错误,并询问他关闭进程。
【问题讨论】:
标签: c++ windows visual-c++ networking
我在 Visual c++ 中创建了一个程序,并在其中实现了一个 Web 服务。 Web 服务设置为监听 80 端口,但如果其他程序已在使用此端口,则 Web 服务无法启动。
所以当webservice无法启动时,我想要一个函数或方法,它可以获取当前使用80端口的进程名称。然后我可以向用户打印一个错误,并询问他关闭进程。
【问题讨论】:
标签: c++ windows visual-c++ networking
GetExtendedTcpTable 和 GetExtendedUdpTable 为您提供网络连接列表。您可以浏览此列表并检查程序是否使用端口 80(它也提供进程 ID)。
【讨论】:
我有一个在 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;
}
【讨论】:
作为第一次尝试,我会考虑将netstat 作为外部进程运行并捕获/解析输出。它为您提供活动连接。
【讨论】:
不确定是否有办法通过 API(不是 Windows 程序员)执行此操作,但是您可以尝试将 netstat -abo 作为 shell 命令,然后在结果字符串中查找 TCP 和端口 80,然后您将具有二进制名称...
编辑:我相信您至少需要 XP SP2 才能使其正常工作...
【讨论】: