windows 查看占用指定端口的进程名称

一 cmd命令
1 查看占用端口的进程ID

#netstat -aon | findstr "10010"

2 查看进程ID的进程名称

#tasklist | findstr "2044"

二 执行cmd命令的windows函数

  1. system
#include 
int system(char *command);
  1. _popen
    create pipes and excute command
FILE *_popen(
    const char *command,
    const char *mode
);
// crt_popen.c
/* This program uses _popen and _pclose to receive a
* stream of text from a system process.
*/

#include 
#include 

int main( void )
{

   char   psBuffer[128];
   FILE   *pPipe;

        /* Run DIR so that it writes its output to a pipe. Open this
         * pipe with read text attribute so that we can read it
         * like a text file.
         */

   if( (pPipe = _popen( "dir *.c /on /p", "rt" )) == NULL )
      exit( 1 );

   /* Read pipe until end of file, or an error occurs. */

   while(fgets(psBuffer, 128, pPipe))
   {
      printf(psBuffer);
   }

   /* Close pipe and print return value of pPipe. */
   if (feof( pPipe))
   {
     printf( "\nProcess returned %d\n", _pclose( pPipe ) );
   }
   else
   {
     printf( "Error: Failed to read the pipe to the end.\n");
   }
}

三 解决方案

std::string GetProcessNameViaPort(int port){
	std::string ret;
	// 获取占用端口的进程ID
	char cmd[256] = {0};
	sprintf_s(cmd, sizeof(cmd) /sizeof(char), "netstat -ano | findstr %d ", port);
	
	FILE * fp;
	fp = _popen(cmd, "r");

	char buff[256] = {0};
	fgets(buff, sizeof(buff)/sizeof(char), fp);
	_pclose(fp);
	fp = NULL;

	if (0x0 == buff[0]){
		return ret;
	}
	std::string str(buff);
	std::string::size_type pos = str.find_last_of(0x20);
	std::string pid;
	if (std::string::npos == pos){
		return ret;
	}
	pid = str.substr(pos + 1, str.length() - pos - 1);

	// 获取进程ID的进程名称
	memset(cmd, 0, sizeof(cmd)/sizeof(char));
	memset(buff, 0, sizeof(buff)/sizeof(char));

	sprintf_s(cmd, sizeof(cmd) /sizeof(char), "tasklist | findstr %s ", pid.c_str());
	fp = _popen(cmd, "r");
	fgets(buff, sizeof(buff)/sizeof(char), fp);
	_pclose(fp);
	
	ret = buff;;
	return ret;
}

你可能感兴趣的:(c++)