抓包命令行工具tshark可以用于自定制,相比GUI工具可以实现一些自动化,譬如把某些关注的数据抓起下来存放到文本中,然后再分析输出。
demo:
std::string decodeHex(const std::string& strHex) { int nLen = strHex.length() / 2; std::string strRet(nLen, 0); for (int i = 0; i != nLen; ++i) { strRet[i] = ((strHex[2*i]>='a') ? (strHex[2*i]-'a'+10) : (strHex[2*i]-'0')) * 16; strRet[i] += (strHex[2*i+1]>='a') ? (strHex[2*i+1]-'a'+10) : (strHex[2*i+1]-'0'); } return strRet; } void cswuyg_test_tshark() { std::wstring strParam = L"\"C:\\Program Files\\Wireshark\\tshark.exe\" -i 1 -p -l -T pdml -f \"dst port 80\" -R \"ip.addr==172.17.195.56\""; FILE* stream = NULL; errno_t err = _wfreopen_s(&stream, L"c:\\temp\\cswuyt_test.xml", L"w", stdout); if (err != 0) { std::cout << "error" << std::endl; } HANDLE hStd = ::GetStdHandle(STD_OUTPUT_HANDLE); //BOOL bSet = ::SetHandleInformation(hStd, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); STARTUPINFO stStartInfo; ZeroMemory(&stStartInfo, sizeof(STARTUPINFO)); stStartInfo.cb = sizeof(STARTUPINFO); stStartInfo.hStdError = hStd; stStartInfo.hStdOutput = hStd; PROCESS_INFORMATION stProcInfo; ZeroMemory(&stProcInfo, sizeof(PROCESS_INFORMATION)); BOOL bSuccess = ::CreateProcess(NULL, const_cast<wchar_t*>(strParam.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &stStartInfo, &stProcInfo); ::CloseHandle(stProcInfo.hProcess); ::CloseHandle(stProcInfo.hThread); ::fclose(stream); }
上边的demo为抓取跟ip地址为172.17.195.56,端口为80(http默认端口)的机器的通信,tshark会提供包解析之后的xml数据,程序将其存储到文件。注意部分数据是需要由hex字符串转换为真实字符串的,另外还可能会有需要gzip解压。