Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ What process is listening on a certain port in windows

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.

like image 963
Kvist Avatar asked Oct 19 '25 10:10

Kvist


2 Answers

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).

like image 160
wj32 Avatar answered Oct 20 '25 23:10

wj32


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;
}
like image 22
ahoo Avatar answered Oct 21 '25 00:10

ahoo