Search code examples
csockets

How to create a buffer for reading socket data in C


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?


Solution

  • 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);