Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a buffer for reading socket data in C

Tags:

c

sockets

Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method. What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character?

like image 480
Heat Miser Avatar asked Sep 27 '08 06:09

Heat Miser


People also ask

What is a buffer in C programming?

C uses a buffer to output or input variables. The buffer stores the variable that is supposed to be taken in (input) or sent out (output) of the program. A buffer needs to be cleared before the next input is taken in.

How does send () work in C?

The send() function shall initiate transmission of a message from the specified socket to its peer. The send() function shall send a message only when the socket is connected (including when the peer of a connectionless socket has been set via connect()).

Is a buffer An array in C?

In C, it is most often an array type. By calling it a buffer, there is an implied meaning that the data stored there is temporary in some sense.


2 Answers

BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is an example:

#define MY_BUFFER_SIZE 1024

char mybuffer[MY_BUFFER_SIZE];
int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);
like image 167
Adam Pierce Avatar answered Nov 07 '22 09:11

Adam Pierce


As always, use sizeof when you have the chance. Using the built-in operator sizeof, you ask the compiler to compute the size of a variable, rather than specify it yourself. This reduces the risk of introducing bugs when the size of the actual variable is different from what you think.

So, instead of doing

#define BUFSIZE 1500
char buffer[BUFSIZE];
int n = read(sock, buffer, BUFSIZE);

you really should use

char buffer[1500];
int n = read(sock, buffer, sizeof buffer);

Notice how you don't need parenthesis around the argument to sizeof, unless the argument is the name of a type.

like image 41
unwind Avatar answered Nov 07 '22 09:11

unwind