Search code examples
c++stringbyterecv

C++ - Client recv function - Bytes to string


I am coming here because I have problem with the recv() function. I am trying to code a TC/IP client which will receive data from a server ( I have not acces to the server code, it is a .exe). I am able to connect and receive the data but then I can not use them. Normaly I should receive a string but in bytes code.

int main()
{
    WSADATA WSAData;
    WSAStartup(MAKEWORD(2,0), &WSAData);//Initialisation du DLL,MAKEWORD(2,0) pour dire que c'est la V2,adresse de la variable qui lance le DLL

    string convert;

    long succes;
    SOCKADDR_IN sin;//info du socket

    int sock, bytes_recieved, bytes_send;
    char send_data[1024], recv_data[2048];

    struct hostent *host;
    struct sockaddr_in server_addr;

    host = gethostbyname("127.0.0.1");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("SocketError");
        exit(1);
    }
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(50500);
    server_addr.sin_addr = *((struct in_addr *) host->h_addr);
    bzero(&(server_addr.sin_zero), 8);


    if (connect(sock, (struct sockaddr *) &server_addr, sizeof(struct sockaddr))
        == -1) {
        perror("ConnectToError");
        exit(1);
    }


    //bytes_send = send(sock, a, strlen(a), 0);
    //bytes_send = shutdown(sock, 1);


    bytes_recieved = recv(sock, recv_data, 2048, 0);    recv_data[bytes_recieved] = '\0';
    printf("\nRecieved data = %s ", recv_data);
    cout << endl << endl;

    shutdown(sock, 2);
    system("PAUSE");
        WSACleanup();


    return 0;
    }

I have value into my array : Array value But I do not know how to translate them into a string, it should follow the following order :

[0:3] Size of the string

[4:n-2] String, each letter on 2 bytes

[n-1:n] End symbole

Thank you for you help.


Solution

  • wendelbsilva already posted the answer, but it was in a comment.

    Do two recv calls. The first call for 4 bytes. Like so:

    unsigned int len;
    assert(sizeof(len) == 4);
    data_receive = recv(sock, &len, 4);
    

    Then you can read the real string.

    std::vector<wchar_t> input(len+1);
    if(data_receive = recv(sock, input.data(), len) != -1)