Avinash
Avinash

Reputation: 13267

Socket read and unknown length data

I am trying to write code in C, in which I want to read a data from a socket, but I do not know the length of the data coming in. I have no control over the data sender.

Is there any way to read socket read using unknown length?

The following is the code I wrote but it hangs in read().

static void
process_command ( int fd ) {
    fprintf ( stderr, "process_command\n" );
    char *buffer = ( char * ) malloc ( sizeof ( char ) * SIZE_TO_READ );
    int n  = 0;
    while ( 1 ) {
        fprintf ( stderr, "." );
        n = read ( fd, buffer, SIZE_TO_READ );
        fprintf ( stderr, "bytes read = %d \n", n );
        if ( n <= 0 || n == -1 )
            break;
        buffer = ( char * ) realloc ( buffer, n + SIZE_TO_READ );
    }
    char * p = strchr ( buffer, '\n' );
    if ( p ) *p = '\0';
    fprintf ( stderr, "-----> %s\n", buffer );
    if ( buffer ) free ( buffer );
}

fd in this case is FILENO_STDIN

Upvotes: 2

Views: 7818

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 598001

It is unusual to not have ANY way of knowing how many bytes to expect. Most protocols have SOME way of specifying either the data length or the data terminator. What kind of protocol are you implementing exactly?

Upvotes: 2

mike.dld
mike.dld

Reputation: 3049

Pass SOCK_NONBLOCK in call to socket() (or call fcntl() with O_NONBLOCK later on) to make socket operations non-blocking. This will result in read() call failing with either EAGAIN or EWOULDBLOCK (those are effectively the same) if there's no data to read (yet).

Alternatively, you may use select() to determine if there's any data ready to be read on a specific socket before the actual read() call.

Upvotes: 1

Elalfer
Elalfer

Reputation: 5348

Just read by some blocks (buffers) until it returns 0 or you'll see that there is an end of the data according to the protocol.

Upvotes: 5

Related Questions