简体   繁体   中英

c++ winsock accept thrown exception

I'm using UE4 4.26.2 github source code,windows 10 1909,visual studio 2019.

code:

// 32-bit unsigned integer
typedef unsigned int        uint32;
// 64-bit unsigned integer
typedef unsigned long long  uint64;

template<typename T32BITS, typename T64BITS>
struct SelectIntPointerType<T32BITS, T64BITS, 8>
{
    // Select the 64 bit type.
    typedef T64BITS TIntPointer;
};
typedef SelectIntPointerType<uint32, uint64, sizeof(void*)>::TIntPointer UPTRINT;

UPTRINT TcpSocketListen(uint16 Port)
{
    // See TcpSocketConnect() for why WSASocket() is used here.
    SOCKET Socket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);

    sockaddr_in SockAddr;
    SockAddr.sin_family = AF_INET;
    SockAddr.sin_addr.s_addr = 0;
    SockAddr.sin_port = htons(Port);
    int Result = bind(Socket, (SOCKADDR*)&SockAddr, sizeof(SockAddr));
    Result = listen(Socket, 1);
    if (!TcpSocketSetNonBlocking(Socket, 1))
    {
        closesocket(Socket);
        return 0;
    }

    return UPTRINT(Socket) + 1;
}

////////////////////////////////////////////////////////////////////////////////
int32 TcpSocketAccept(UPTRINT Socket, UPTRINT& Out)
{
    SOCKET Inner = Socket - 1;

    Inner = accept(Inner, nullptr, nullptr);

}

static UPTRINT          GControlListen      = 0;
GControlListen = TcpSocketListen(1985);
UPTRINT Socket;
int Return = TcpSocketAccept(GControlListen, Socket);

when debuging, visual studio catch a C++ exception in line:accept(Inner, nullptr, nullptr);

output: Exception thrown at 0x00007FFCDF673B19 (in UE4Editor-Win64-Debug.exe): Microsoft C++ Exception: int at memory location 0x0000001F892FFC38.

Best wishes, Dian

The socket docs on accept:

The argument sockfd is a socket that has been created with socket(2), bound to a local address with bind(2), and is listening for connections after a listen(2).

So the first argument must just be a socket descriptor. You are casting that socket to a pointer, add 1 to the address which completely changes the value of the returned value in socket. Then pass that number to accept and subtract one. The socket library has no clue what that number means anymore and crashes.

Just use the raw value returned from the socket library in subsequent calls.

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