#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
BOOL FindFirstFileExists(LPCTSTR lpPath, DWORD dwFilter)
{
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(lpPath, &fd);
BOOL bFilter = (FALSE == dwFilter) ? TRUE : fd.dwFileAttributes & dwFilter;
BOOL RetValue = ((hFind != INVALID_HANDLE_VALUE) && bFilter) ? TRUE : FALSE;
FindClose(hFind);
return RetValue;
}
/*
* 检查一个 路径 是否存在(绝对路径、相对路径,文件或文件夹均可)
* 存在则返回 1 (TRUE)
*/
BOOL FilePathExists(LPCTSTR lpPath)
{
return FindFirstFileExists(lpPath, FALSE);
}
string _get_output(void) {
string output;
FILE *fp;
// 这里生成脚本。
if (FilePathExists(L"getport.bat") != TRUE) {
fopen_s(&fp, "getport.bat", "w");
const char *_cmd = "del input.txt /F /Q\n\nnetstat -ano > input.txt\n\necho OKKK >> input.txt";
fwrite(_cmd, sizeof(char), strlen(_cmd), fp);
fclose(fp);
}
//执行脚本,获得所有的端口。
WinExec("getport.bat", SW_HIDE);
// 等待文件生成。
while (FilePathExists(L"input.txt") != TRUE);
fopen_s(&fp, "input.txt", "r");
if (NULL == fp) {
printf("找不到这个文件!\n");
printf("不能打开input.txt获得端口列表。!\n");
}
// 这里去获得整个文件的内容。
char *content;
int length = 0;
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, 0, SEEK_SET);
content = (char *)malloc(sizeof(char) * length);
memset(content, 0, length);
fread_s(content, length, sizeof(char), length, fp);
output = content;
free(content);
fclose(fp);
return output;
}
set<int> get_port_list(string &input) {
vector<string> lines;
string temp;
for (size_t i = 0; i < input.length(); ++i) {
if (input[i] == '\n' || input[i] == '\r') {
lines.push_back(temp);
temp = "";
//printf("%s\n", temp.c_str());
} else {
temp = temp + input[i];
}
}
set<int> vs;
// 这里处理每一行。
for (size_t i = 0; i < lines.size(); ++i) {
// 这里从每一行中拿到端口。
string line = lines[i];
size_t tcp_pos = line.find("TCP");
size_t udp_pos = line.find("UDP");
// 如果没有找到,那么看下一行。
if (tcp_pos == string::npos && udp_pos == string::npos) {
continue;
}
size_t pos;
if (tcp_pos != string::npos) pos = tcp_pos;
if (udp_pos != string::npos) pos = udp_pos;
// 找到了相应的位置。3表示tcp/UDP字符串的长度,strlen(tcp) == 3
line = line.substr(pos + 3, line.length());
// front_pos;
size_t iter = 0;
size_t front_pos = 0;
size_t end_pos = 0;
// 这里找到第一个字符串开头的位置。
while (iter < line.length() && isspace(line[iter])) iter++;
front_pos = iter;
// 这里找到结束的位置。
while (iter < line.length() && !isspace(line[iter])) iter++;
end_pos = iter;
// 找到了第二列。
string word = line.substr(front_pos, end_pos - front_pos);
// 这里找到最后一个:号的位置。
word = word.substr(word.find_last_of(':') + 1, word.length());
int port = atoi(word.c_str());
vs.insert(port - 1);
vs.insert(port);
vs.insert(port + 1);
}
return vs;
}
int main(void) {
string input = _get_output();
set<int> vs = get_port_list(input);
for (set<int>::iterator iter = vs.begin(); iter != vs.end(); ++iter) {
printf("%d\n", *iter);
}
return 0;
}
版权声明:本文为ju136原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。