C++ 运行 虚拟 nat 网络上 winsock 的时间内存错误

C++ Run time memory error with winsock on virtual nat network

我有一个我编写的服务器,可以将计算机的文件系统解析为一个向量。然后客户端使用 Putty 或 netcat 连接到服务器并接收解析文件系统的向量。

这在一台 127.0.0.1 的机器上本地工作正常。

但是,当我在 10.0.0.0 NAT 网络上将代码传输到 VirtualBox 中的虚拟环境时,我收到内存错误。

有什么解决办法吗?

这是我的代码:

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <filesystem>
#include <vector>
#include <string>
namespace fs = std::filesystem;

std::vector<std::string> get_all_files_recurisive(const std::string& path)
{
    std::vector<std::string> file_names;

    using iterator = fs::recursive_directory_iterator;
    for (iterator iter(path); iter != iterator{}; ++iter)

        file_names.push_back(iter->path().string());
    return file_names;
}

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "45000"
#define DEFAULT_ADDRS "10.0.2.5"
int __cdecl main(void)
{
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;
    

    struct addrinfo* result = NULL;
    struct addrinfo hints;

    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    

    // Resolve the server address and port
    iResult = getaddrinfo(DEFAULT_ADDRS, DEFAULT_PORT, &hints, &result);
    if (iResult != 0) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // No longer need server socket
    closesocket(ListenSocket);

    // Receive until the peer shuts down the connection
    do {
       
        std::string SendIresult = "";
        const std::vector<std::string> file_list = get_all_files_recurisive("C:\Users");
        for (const auto& fn : file_list) {
            // Convert fn vector in the for loop to sendable data
            const char* sendbuf = fn.data();


            iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
            if (iResult > 0) {
                printf("Bytes received: %d\n", iResult);



                // Echo the fn vector list to the sender
                iResult = send(ClientSocket, sendbuf, (int)strlen(sendbuf), 0);
                if (iResult == SOCKET_ERROR) {
                    printf("send failed with error: %d\n", WSAGetLastError());
                    closesocket(ClientSocket);
                    WSACleanup();
                    return 1;
                }
                printf("Bytes sent: %d\n", iResult);
            }
            else if (iResult == 0)
                printf("Connection closing...\n");
            else {
                printf("recv failed with error: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
        }

    } while (iResult > 0);

    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;
}

这是我在 VM 上 运行 中的 Visual Studio 并尝试从同一网络上的 parrot-os Linux 连接 netcat 时出现的错误:

这是文本中的错误消息:

Unhandled exception at 0x75772552 in Project3.exe: Microsoft C++ exception: std::system_error at memory location 0x0141EA50.

它发生在开头这一行之后。

using iterator = fs::recursive_directory_iterator;
for (iterator iter(path); iter != iterator{}; ++iter)

仅供参考,此代码并未发布,因此无需编写最漂亮的代码。它用于漏洞利用开发项目。

您正在看到来自 Visual Studio 调试器的消息。它告诉您代码正在抛出您未处理的 std::system_error 异常。

如果底层 OS 文件系统 API 失败,您正在调用的 recursive_directory_iterator 构造函数将抛出一个 std::filesystem::filesystem_error 异常(std::system_error 的派生),例如好像提供的 path 无效等。因此,您需要:

  • catch那个异常并处理它:

    try
    {
        for (iterator iter(path); iter != iterator{}; ++iter)
            file_names.push_back(iter->path().string());
    }
    catch (const fs::filesystem_error &e)
    {
        // do something, such as logging the values of e.what(), e.path1(), and e.code() ...
    }
    
  • 使用重载构造函数和 increment() 方法,它采用 std::error_code& 输出参数:

    std::error_code ec;
    iterator iter(path, ec);
    while ((!ec) && (iter != iterator{})){
        file_names.push_back(iter->path().string());
        iter.increment(ec);
    }
    if (ec) {
        // do something, such as logging the values of ec.value() and ec.message() ...
    }