Reputation: 75
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.
Upvotes: 3
Views: 5358
Reputation: 1361
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;
}
Upvotes: 1
Reputation: 8463
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).
Upvotes: 4
Reputation: 33655
Not sure if there is a way to do this via an API (not a windows programmer), however you could try netstat -abo as a shell command, then look for TCP and port 80 in the resulting string, and you'll have the binary name...
EDIT: I believe you need XP SP2 atleast for this to work...
Upvotes: 0
Reputation: 882586
I would consider, as a first attempt, running netstat
as an external process and capturing/parsing the output. It gives you the active connections.
Upvotes: 0