最近写个程序需要获取本机用于连接的IP地址,经过很多的尝试后,最终使用的方法如下:
- 使用cmd命令 netstat | findstr “192.168.6.66:3333” > D:\\localAddress.txt
其中“192.168.6.66:3333”是我的程序连接的服务器的ip地址,运行netstat命令后,找到其中包含了“192.168.6.66:3333”的那一行,并将结果输出到 localAddress.txt 中,localAddress.txt中的结果可能如下图所示
2.读取 localAddress.txt 中的内容,并解析出本机用于连接的ip地址为 192.168.4.45
- 我是使用CreateProcess函数运行cmd命令,可以避免出现cmd命令窗口,也能等待cmd命令运行结束再往下运行。
代码如下:
1 std::string path = "D:\\localAddress.txt"; 2 //创建用于保存本机IP地址的localAddress.txt 3 std::ofstream fout(path); 4 if (fout) // 如果创建成功 5 { 6 fout << "" << std::endl; 7 fout.close(); // 执行完操作后关闭文件句柄 8 9 std::string ptr; 10 std::string output; 11 ptr="cmd /c netstat | findstr \"192.168.6.66:3333 > "; 12 ptr += path; 13 14 STARTUPINFO si; 15 PROCESS_INFORMATION pi; 16 17 ZeroMemory(&si, sizeof(si)); 18 si.cb = sizeof(si); 19 //隐藏掉可能出现的cmd命令窗口 20 si.dwFlags = STARTF_USESHOWWINDOW; 21 si.wShowWindow = SW_HIDE; 22 ZeroMemory(&pi, sizeof(pi)); 23 24 // Start the child process. 25 if (CreateProcess(NULL, // No module name (use command line) 26 (LPSTR)(LPCTSTR)ptr.c_str(), // Command line 27 NULL, // Process handle not inheritable 28 NULL, // Thread handle not inheritable 29 FALSE, // Set handle inheritance to FALSE 30 0, // No creation flags 31 NULL, // Use parent's environment block 32 NULL, // Use parent's starting directory 33 &si, // Pointer to STARTUPINFO structure 34 &pi) // Pointer to PROCESS_INFORMATION structure 35 ) 36 { 37 38 // Wait until child process exits. 39 WaitForSingleObject(pi.hProcess, INFINITE); 40 41 std::fstream ffileTemp(path); //作为读取文件打开 42 if (ffileTemp) 43 { 44 char buffer[256]; 45 while (!ffileTemp.eof()) 46 { 47 ffileTemp.getline(buffer, 256, '\n'); 48 std::string temp = buffer; 49 if (temp.find("ESTABLISHED") != std::string::npos) 50 { 51 output += temp; 52 break; 53 } 54 } 55 ffileTemp.close(); 56 } 57 58 if (output.length() > 0) 59 { 60 output.erase(0, output.find_first_not_of(" ")); 61 std::string localip, temp; 62 temp = output.substr(output.find_first_of(" ")); 63 temp.erase(0, temp.find_first_not_of(" ")); 64 temp = temp.substr(0, temp.find_first_of(" ")); 65 66 localip = temp.substr(0, temp.find_first_of(":")); //获得ip地址 67 68 } 69 } 70 }