您的位置:首页 > 其它

读取相关连接的物理地址

2016-04-01 22:05 267 查看
利用上次的匿名管道就可以读取cmd命令的相关信息

将其写成类CmdInfoToPile

CmdInfoToPipe.h

1 #ifndef NETINFO_CMDINFOTOPIPE_H_
2 #define NETINFO_CMDINFOTOPIPE_H_
3 #include <windows.h>
4 #include <stdio.h>
5 #include <string>
6 #include <vector>
7
8 class CmdInfoToPipe
9 {
10 public:
11     CmdInfoToPipe();
12     ~CmdInfoToPipe();
13     DWORD getCmdInfo(char *cmd);//匿名管道读取cmd信息
14     std::vector<std::string> get_Mac_Address(std::string strconnect = "本地连接", std::string straddress = "物理地址");//读取物理地址
15 private:
16     std::string strcmd_;
17     std::string cmd_;
18 };
19 #endif//CmdInfoToPipe.h


CmdInfoToPipe.cpp

#include "CmdInfoToPipe.h"

CmdInfoToPipe::CmdInfoToPipe()
{
cmd_ = "Cmd.exe /C ";
strcmd_ = "";
}

CmdInfoToPipe::~CmdInfoToPipe()
{
}

std::vector<std::string>  CmdInfoToPipe::get_Mac_Address(std::string strconnect, std::string straddress){
int connect = 0;
int address = 0;
printf("%s %s\n", strconnect.c_str(), straddress.c_str());
std::vector<std::string> vstr;

while ((connect = strcmd_.find(strconnect, connect)) != std::string::npos){//可能有多个这种连接
if((address = strcmd_.find(straddress, connect + 1)) != std::string::npos){
if ((address = strcmd_.find("-", address + 1)) != std::string::npos){
vstr.push_back(strcmd_.substr(address - 2, 17));
connect = address + 16;
}
}
}

return vstr;
}
DWORD CmdInfoToPipe::getCmdInfo(char *cmd){
cmd_ +=std::string(cmd);
char mycmd[100];
sprintf_s(mycmd, "%s", cmd_.c_str());
char Buffer[4096];
STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
SECURITY_ATTRIBUTES sa;
HANDLE hRead, hWrite;
DWORD bytesRead;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;

if (!CreatePipe(&hRead, &hWrite, &sa, 0)) //创建匿名管道
{
return GetLastError();
}

GetStartupInfo(&sInfo);
sInfo.cb = sizeof(sInfo);
sInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
sInfo.wShowWindow = SW_HIDE;
sInfo.hStdError = hWrite;   //将管道的写端交给子进程
sInfo.hStdOutput = hWrite;
memset(&pInfo, 0, sizeof(pInfo));

if (!CreateProcess(NULL, mycmd, NULL, NULL, TRUE, 0, NULL, NULL, &sInfo, &pInfo)) //创建子进程
{
CloseHandle(hWrite);
CloseHandle(hRead);
return GetLastError();
}
CloseHandle(hWrite); //关闭父进程的写端
strcmd_ = "";

for (int i = 0;; ++i)
{
if (!ReadFile(hRead, Buffer, sizeof(Buffer) - 1, &bytesRead, NULL)) //读取内容
{
break;
}
Buffer[bytesRead] = 0;
strcmd_ += std::string(Buffer);//防止出现查找字符分散在各个BUFFER中
}

WaitForSingleObject(pInfo.hProcess, INFINITE);
CloseHandle(hRead);
return GetLastError();
}


测试代码

#include <CmdInfoToPipe.h>
#include <cstdio>
#include<vector>
#include<string>
int main()
{
char *mycmd = "ipconfig/all";
CmdInfoToPipe pCItP;
pCItP.getCmdInfo(mycmd);
std::vector<std::string> vtr = pCItP.get_Mac_Address("无线网络连接");
for (auto i : vtr){
printf("%s\n", i.c_str());
}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: