0

I am working on BSD sockets and I use this function

int recvfrom( int socket , void *buffer , size_t nbytes , int flags , struct sockaddr *sender , int *addrlen)

but before printing a message in server I want to save value of buffer in array of char and make some operations. How to do it?

EDIT: example

Buffer stores a message "Hello", my array should look like arr[]={'h','e','l','l','o'}

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
L.krez
  • 31
  • 5

1 Answers1

1

recvfrom() function

int recvfrom( int socket , void *buffer , size_t nbytes ,
              int flags , struct sockaddr *sender , int *addrlen);

allows the user to receive data from an UDP socket. On success (return value > 0) it returns the number of received bytes, writing up to nbytes bytes to memory area pointed by buffer. Originator's address and its len are also written by the function respectively in sender and addrlen pointers provided by the caller.

So, in order to have incoming bytes in your char array (chars are bytes!) you simply have to pass it to the recvfrom as buffer parameter.

#define MAX_RECV_BUF_LEN 100

char arr[MAX_RECV_BUF_LEN + 1];
struct sockaddr senderAddr;
int addrLen, res;

res = recvfrom( yourSocketDescr , arr, MAX_RECV_BUF_LEN, yourFlags , &senderAddr, &addrLen);
if ( res > 0 )
{
  arr[res] = 0; // Add a string terminator. Useful only if you expect 'printable' data

  // ... some operations
}
/* else... manage errors */
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39