質問

Can anyone tell me how to identify which process is running in certain port in Windows using C/C++. I want to write a simple port scanner. When I find some ports are opened, I also want to print which process is running in each port. Thanks.

役に立ちましたか?

解決

#include <stdio.h>
#include <string>

void executeCMD(const char *cmd, char *result)
{
    char buf_ps[1024];
    char ps[1024]={0};
    FILE *ptr;
    strcpy(ps, cmd);
    if((ptr=popen(ps, "r"))!=NULL)
    {
        while(fgets(buf_ps, 1024, ptr)!=NULL)
        {
            strcat(result, buf_ps);
            if(strlen(result)>1024)
                break;
        }
        pclose(ptr);
        ptr = NULL;
    }
    else
    {
        printf("popen %s error\n", ps);
    }
}

int main()
{
    char result[1024];
    executeCMD( "netstat -ano", result);
    printf("%s", result );
    return 0;
}

maybe, you could have a try!

他のヒント

I have a solution using Qt in C++:

/**
 * \brief Find all ids of processes that is listening to any port.
 * \return A key-value map that keys are ports and values are corresponding process id.
 */
QMap<uint, uint> findAllProcessesListeningToAnyPort()
{
   QMap<uint, uint> portToProcessId;
   QString netstatOutput;
   {
      QProcess process;
      process.start("netstat -ano -p tcp");
      process.waitForFinished();
      netstatOutput = process.readAllStandardOutput();
   }
   QRegularExpression processFinder;
   {
      const auto pattern = R"(TCP[^:]+:(?<port>\d+).+LISTENING\s+(?<pid>\d+))";
      processFinder.setPattern(pattern);
   }
   auto processInfoItr = processFinder.globalMatch(netstatOutput);
   while (processInfoItr.hasNext())
   {
      const auto processInfo = processInfoItr.next();
      const auto port = processInfo.captured("port").toUInt();
      const auto processId = processInfo.captured("pid").toUInt();
      portToProcessId.insert(port, processId);
   }
   return portToProcessId; 
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top