我正在做一个C++项目。为了满足其中一个需求,我需要随时检查应用程序中是否有可用的端口。为了实现这一点,我得到了以下解决方案。
#include <iostream>
#include <cstdlib>
#include <stdexcept>
#include <string>
#include <stdio.h>
std::string _executeShellCommand(std::string command) {
char buffer[256];
std::string result = "";
const char * cmd = command.c_str();
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe))
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
bool _isAvailablePort(unsigned short usPort){
char shellCommand[256], pcPort[6];
sprintf(shellCommand, "netstat -lntu | awk '{print $4}' | grep ':' | cut -d \":\" -f 2 | sort | uniq | grep %hu", usPort);
sprintf(pcPort, "%hu", usPort);
std::string output = _executeShellCommand(std::string(shellCommand));
if(output.find(std::string(pcPort)) != std::string::npos)
return false;
else
return true;
}
int main () {
bool res = _isAvailablePort(5678);
return 0;
}在这里,基本上_executeShellCommand函数可以随时执行任何外壳命令,并且可以将stdout输出作为返回字符串返回。
我在该函数中执行以下shell命令。
netstat -lntu | awk '{print $4}' | grep ':' | cut -d \":\" -f 2 | sort | uniq | grep portToCheck因此,如果端口已在使用中,_executeShellCommand将返回PortValue本身,否则将返回空白。所以,检查返回的字符串,我可以决定。
到目前一切尚好。
现在,我想让我的项目完全防崩溃。因此,在启动netstat命令之前,我想确认它是否真的存在。在这种情况下我需要帮助。我知道,怀疑netstat命令在linux机器上的可用性是很愚蠢的。我只是在想某个用户出于某种原因从他的机器上删除了netstat二进制文件。
注意:如果端口可用或不可用,我不想向chack发出bind()调用。另外,如果我可以在不调用_executeShellCommand的情况下检查netstat命令是否可用(即不执行另一个外壳命令),那将是最好的。
发布于 2016-09-21 21:13:38
一个更好的想法是让你的代码完全不需要netstat就能工作。
在Linux上,netstat所做的(对于您的用例)就是读取/proc/net/tcp的内容,它会枚举所有正在使用的端口。
您所要做的就是自己打开/proc/net/tcp并对其进行解析。这只是一个普通的、无聊的文件解析代码。没有比这更好的“防崩溃”了。
您可以在Linux手册页中找到/proc/net/tcp格式的文档。
在不太可能的情况下,您需要检查UDP端口,这将是/proc/net/udp。
当然,在您检查/proc/net/tcp的时间之间有一个竞争窗口,在这个窗口中有人可以抢占端口。但对于netstat也是如此,因为这将是一个慢得多的过程,这实际上是一个改进,并显着减少了竞争窗口。
发布于 2016-09-21 21:28:32
由于您正在询问一种检查netstat命令是否可用的方法,因此我不会尝试在C++中建议其他方法。shell方式正在检查以下命令的返回码:
command -v netstat如果$PATH中提供了netstat二进制文件,则该命令返回0。在Bash中,它通常如下所示:
command -v netstat
if [ $? -eq 0 ]; then
netstat # ...
else
echo >&2 "Error: netstat is not available"
fi或者简单地说
command -v netstat >/dev/null && netstat # ...https://stackoverflow.com/questions/39617324
复制相似问题