任何人都可以告诉我如何使用C / C ++识别Windows中某个端口正在运行的进程。我想写一个简单的端口扫描器。当我发现打开一些端口时,我还想打印每个端口正在运行的进程。 感谢。
答案 0 :(得分:0)
#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;
}
也许,你可以尝试一下!
答案 1 :(得分:0)
我有在C ++中使用Qt的解决方案:
/**
* \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;
}