简体   繁体   中英

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

I have a Server that I wrote that parses the computer's filesystem into a vector. A client then connects to the server with Putty or netcat and receives the vector of the parsed filesystem.

This works fine locally on one machine with 127.0.0.1.

However, when I transfer the code to a virtual environment in VirtualBox on a 10.0.0.0 NAT network, I receive a memory error.

Any ideas how to fix this?

Here is my code:

#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;
}

Here is the error when I run it in Visual Studio on the VM and tried connecting with netcat from my parrot-os Linux on the same network:

运行时内存错误

Here is the error message in text:

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

It happens right after this line in the beginning.

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

Just for context, this code is not being published, so it doesn't need to be the prettiest code written. It's for an Exploit dev project.

You are seeing a message from the Visual Studio debugger. It is telling you that the code is throwing a std::system_error exception that you are not handling.

The recursive_directory_iterator constructor you are calling throws a std::filesystem::filesystem_error exception (a derivative of std::system_error ) if the underlying OS filesystem API fails, such as if the provided path is invalid, etc. So, you need to either:

  • catch that exception and handle it:

     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()... }
  • use the overloaded constructor, and increment() method, which take a std::error_code& output parameter:

     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()... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM