我在Visual C++中创建了一个程序,其中实现了一个Web服务。Web服务被设置为在端口80上侦听,但如果另一个程序已经正在使用此端口,则Web服务无法启动。
因此,当Web服务无法启动时,我希望有一个函数或方法可以获取当前使用端口80的进程名称。然后我可以向用户打印错误,并要求他关闭该进程。
我在Visual C++中创建了一个程序,其中实现了一个Web服务。Web服务被设置为在端口80上侦听,但如果另一个程序已经正在使用此端口,则Web服务无法启动。
因此,当Web服务无法启动时,我希望有一个函数或方法可以获取当前使用端口80的进程名称。然后我可以向用户打印错误,并要求他关闭该进程。
GetExtendedTcpTable和GetExtendedUdpTable可以提供一个网络连接列表。你可以遍历这个列表,并检查一个程序是否使用了80端口(它还提供了进程ID)。
/**
* \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才能使其正常工作...