Search code examples
c++dllhookwinsock2detours

C++ Winsock recv hook Detours


i want to write a .dll. My Targetapplication is a Game and use winsock. The .dll should write all things in a Console what the Game (Targetapplication) recives through the recv function in winsock. I've created a C++ Win32 Console Application in Visual Studio 2012 Professional, choosed .dll and Empty project.

My Code in main.cpp

#include <Windows.h>
#include <detours.h>
#include <winsock2.h>
#include <iostream>

using namespace std;

#pragma comment (lib, "detours")

typedef int (WINAPI *MyRecv) (SOCKET, char, int, int);

MyRecv OrigRecv = NULL;

int WINAPI RecvDetour(SOCKET s, char *buf, int len, int flags)
{
    cout << *buf << "   -   " << len << endl;
    return OrigRecv(s, *buf, len, flags);
}


BOOL APIENTRY DllMain(HINSTANCE module, DWORD Reason, LPVOID reserved)
{
    switch (Reason)
    {
    case DLL_PROCESS_ATTACH:
        cout << "Starting.." << endl;
        OrigRecv = (MyRecv)DetourFunction((PBYTE)recv, (PBYTE)RecvDetour);
        break;
    case DLL_PROCESS_DETACH:
        break;
    }
}

I don't able to compile this. There are some Errors. Do anybody see a error in this code?

Thank you very much :)


Solution

  • MyRecv is declared wrong. The second parameter needs to be char* instead of char.

    Also, your detour is outputting the receive buffer before it has been populated. You need to call the original recv() function first and then you can output what it receives. Also, be sure to take into account that the data will not be null terminated.

    typedef int (WINAPI *MyRecv) (SOCKET, char*, int, int);
    
    MyRecv OrigRecv = NULL;
    
    int WINAPI RecvDetour(SOCKET s, char *buf, int len, int flags)
    {
        int ret = OrigRecv(s, buf, len, flags);
        if (ret > 0)
            cout.write(buf, ret) << "   -   " << ret << endl;
    }
    

    See this earlier question:

    Detour hook send/recv winsock