I have created a program in visual c++, where i have implemented a web service. The web service is set to listen on port 80, but if another program already is using this port, the web service fail to start up.
So when the webservice can't start, I would like to have a function or method, which can get the name of the process, that currently uses port 80. Then i can print an error to the user, and ask him to close the process.
GetExtendedTcpTable and GetExtendedUdpTable give you a list of network connections. You can walk through this list and check if a program is using port 80 (it provides process IDs as well).
I have a solution using Qt in C++:
/**
* \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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With