使用C查找使用某端口的进程名

来源:互联网 发布:lnmp源码编译安装 编辑:程序博客网 时间:2024/05/16 08:17

    在windows下查找进程使用的端口是比较容易的,在cmd命令行模式下,使用netstat -ano即可;但是如果,想要在程序中自己实现,就需要做点修改了。

    从网上查找的相关资料表明,可以有几种方法实现:

    一、借用 netstatp 早期的开源项目,C形式封装的,非常好用,但缺点是,查找结果不完善。 而新版本的又无法获取源码。

    二、借用 TcpView ,这个是 netstatp 的新版本界面版,功能与windows自带 netstat 功能相当,现在已经有“好事者“汉化,直接百度即可得到源码。

    三、调用 windows 相关接口,以变通实现cmd命令,具体查明的有四个:WinExec、ShellExecute、CreateProcess、system。

    下面是其中的一种方法:

    main.cpp

#include <stdlib.h>#include <stdio.h>#include <string>using namespace std;bool GetNameByPort(int nPort, string &strResult){char pResult[128] = {0};const char* pPortFilePath = "c:\\~vkutmp";const char* pProcessFilePath = "c:\\~vvkutmp";sprintf(pResult, "netstat -ano|findstr %d > %s",  nPort, pPortFilePath);system(pResult);FILE *pPortFile = fopen(pPortFilePath, "r");if ( NULL != pPortFile ){fread(pResult, 1, sizeof(pResult), pPortFile);strResult = pResult;if ( "" != strResult ){int off = strResult.find_last_of(0x0a);if ( off > -1 ){strResult = strResult.substr(0, off);off = strResult.find_last_of(0x20);if ( off > -1 ){strResult = strResult.substr(off+1);sprintf(pResult, "tasklist|findstr %s > %s", strResult.c_str(), pProcessFilePath);system(pResult);FILE *pProcessFile = fopen(pProcessFilePath, "r");if ( NULL != pProcessFile ){memset(pResult, 0, sizeof(pResult));fread(pResult, 1, sizeof(pResult), pProcessFile);strResult = pResult;if ( "" != strResult ){off = -1;off = strResult.find_first_of(0x20);if ( off > -1 ){strResult = strResult.substr(0, off);return true;}}}fclose(pProcessFile);pProcessFile = NULL;sprintf(pResult, "del %s", pProcessFilePath);system(pResult);}}}}strResult = "";fclose(pPortFile);pPortFile = NULL;sprintf(pResult, "del %s", pPortFilePath);system(pResult);return false;}int main(){string strResult = "";bool bo = GetNameByPort(80, strResult);printf("%s", strResult.c_str());system("pause");return 1;}

转载请注明来自Master.R(石硕)的CSDN博客:blog.csdn.net/shishuo365  如有疑问请发邮件shishuo365#126.com(将#更换为@)

原创粉丝点击