Question

I need to write a windows sockets application for work, but having virtually no experience with network programming I'm in need of a little assistance.

I need to make several functions to make requests for different data from a server, lets use one of those things, random numbers, as an example.

DWORD GetRandomNumbers(int amount, int* buffer, int bufferSize);

the method returns a DWORD representing either success, or an error message, and must get the buffer from the calling function which can call it like so:

int numbers[10];
GetRandomNumbers(10,numbers,10);

Inside the function:

//set up packet containing request
//send the packet
//then call recv
recv(m_socket, (char*)buffer, bufferSize, 0);
//now cast the char array to a struct defining the incoming message packet
RandNumPacketIn* p = (RandNumPacketIn*)buffer;

OK. Now within 'p' is an array of random numbers from the server - great! Except 'p' also contains other data which is part of the incoming packet. What I would like is for the buffer which is passed in to just contain the random numbers when I'm done. If I knew the structure of the incoming packet and it was something like:

struct incomingrandnums
{
    int a;
    int b;
    char c;
    int numbers[100];
}   

is it possible to create a char* in the function and allocate memory for the first three members in the packet, then just memcpy the passed in buffer to the end? Perhaps not exactly like that, but you get my drift, the result should be that the calling function can just create an array of ints, pass its address to the function and when its done the array in the calling function contains just the random numbers that were in the received packet. I cant test this out until work tomorrow but it's been on my mind.

Thanks.

Was it helpful?

Solution

You would need to use two separate buffers. One buffer that the function uses to receive the entire packet, and then the caller's buffer that receives just the portions of the packet that the caller is interested in. For example:

struct packet
{
    int a;
    int b;
    char c;
    int numbers[100];
};   

struct randnums
{
    int a;
    int b;
    char c;
};   

DWORD GetRandomNumbers(randnums &nums)
{
    packet pckt;
    recv(m_socket, (char*)&pckt, sizeof(pckt), 0);
    memcpy(&nums, &pckt, sizeof(nums));
}

{
    randnums numbers;
    GetRandomNumbers(numbers);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top