Search code examples
c++socketssdlsdl-net

Converting an int to void *data and getting the length in bytes


I am trying to use the SDLNet_TCP_Send(TCPsocket sock, void *data, int len) function (part of the SDL_net library) and I am having a hard time figuring out how I could use this to send an int. Would I be able to do that or should I use another approach?


Solution

  • "how I could use this to send an int ... Would I be able to do that or should I use another approach?"

    The function can be used to do so. You just use an address and sizeof():

    int dataToSend = 42;
    SDLNet_TCP_Send(sock, &dataToSend, sizeof(dataToSend)); 
    

    Depending on the data protocol you might need to obey that integer data should be sent in network byte order (to have it machine architecture independend):

    #include <arpa/inet.h>
    
    int dataToSend = htonl(42);
                  // ^^^^^ Make integer network byte ordered (big endian)
    SDLNet_TCP_Send(sock, &dataToSend, sizeof(dataToSend));