Link to home
Start Free TrialLog in
Avatar of imranqurai
imranqurai

asked on

sending and receiving 2D array using UDP

I am trying to send and recieve a 5x5 int array.

In my code I have for sending(UDP) int distvector[5][5]:

        remoteServAddr.sin_port = htons(5000+i*1000);
        rc = sendto(sd, &distvector, sizeof((int)distvector[5][5]), 0,
        (struct sockaddr *) &remoteServAddr,
        sizeof(remoteServAddr));


And for recieving I have (UDP) int recv_DV[5][5]:

        recvfrom(sd, &recv_DV, sizeof((int)recv_DV[5][5]), 0,
         (struct sockaddr *) &cliAddr, &cliLen);

i dont recieve the right array, recv_DV[0][0] has an odd number in it (I suppose its the array's address) and the rest of the array is '0'.  Also in the sendto() function I used distvector instead of &distvector but still the same result.

ne help would be much appreciated.

thnxs
ASKER CERTIFIED SOLUTION
Avatar of grg99
grg99

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
-----> rc = sendto(sd, &distvector, sizeof((int)distvector[5][5]), 0,
        (struct sockaddr *) &remoteServAddr,
        sizeof(remoteServAddr));


U are using sizeof ( (int) distvector[5][5] ) ---.> This would give u the size of the last element in your array i.e. the size of int on your machine

For getting the size of whole array, u should use         sizeof ( distvector )
Same comment above applies to recvfrom also
Also I don't think you would need to pass &distvector in sendto OR recvfrom

both these functions expect a void pointer *. So U can just pass szDataFromUdp as the second parameter to sendto and recvfrom.

Basically the second parameter expects the starting address of the data to be passed and the amount of data passed is governed by the next parameter.

Thus only using szDataFromUdp  as second parameter would give u the base address of the data and sizeof( szDataFromUdp ) would give u the amount of data to be passed
Avatar of Ajar
Ajar

Your code looks clean and should work .. just a suggestion calculate the length before hand and use that in send and recv functions like

//for sending
int distvector[5][5],len;
len = sizeof(distvector);
sendto(sd,&distvector,len,0,(struct sockaddr *) &remoteServAddr,sizeof(remoteServAddr);

// for receiving
int recv_DV[5][5],len;
len = sizeof(recv_DV);
recvfrom(sd, &recv_DV, len, 0,(struct sockaddr *) &cliAddr, &cliLen);
Hi Ajar,

I think, as I already posted, the second parameter shoudl be distvector and NOT &distvector

Your code would pass the len amount of data starting from ADDRESS of distvector


Sorry Guys,

I am really sorry

Did not come to mind that distvector and &distvector would be same