先说一下我的编程环境:linux(centos版本),eclipse CDT。
下面是在linux下检查端口号的一段代码。在执行的时候,总是不能得到完整的端口号信息,后来分析是因为权限不同。
做法:在终端中,先进入root,然后打开eclipse,这样程序就是在root下运行的,得到的命令行信息就完整了。
//============================================================================ // Name : test1.cpp // Author : jin // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <cstdlib> #include <string> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; void Test(int port) { string portString = std::to_string (port); //cout << portString; char line[300]; FILE *fp; //检查端口号 string cmdPort = "netstat -anp |grep :"; cmdPort = cmdPort + portString; // 系统调用 const char *sysCommand = cmdPort.data(); //如果没有打开端口 if ((fp = popen(sysCommand, "r")) == NULL) { cout << "error" << endl; return; } //如果端口号打开了, while (fgets(line, sizeof(line)-1, fp) != NULL) { cout << line ; // } pclose(fp); } int main() { Test(443); return 0; }