Pete.Mertz
Pete.Mertz

Reputation: 1301

Recv only gets 8 characters at a time

So, I'm trying to figure out the socket library in C, and I'm running into problems reading messages using recv. It seems that when the server receives a message, it always reads 8 characters, regardless of the message sent or the buffer size (as long as its >= 8).

On top of this, sending messages in rapid succession makes it so that only the first message gets through, is there some reset time and I'm improperly closing the socket?

Here's my server code so far:

void main( void ) {
  printf( "Starting Server...\n" );
  int sock = socket( AF_INET, SOCK_STREAM, 0 );

  struct sockaddr_in server, client;

  server.sin_family = AF_INET;
  server.sin_port = htons( 3030 );
  server.sin_addr.s_addr = htonl( INADDR_ANY );

  bind( sock, (const struct sockaddr*)&server, sizeof( server ) );
  listen( sock, 5 );

  while ( 1 ) {
    int cli_len = sizeof( client );
    int client_socket = accept( sock, (struct sockaddr*)&client, &cli_len );
    conn_made( client_socket );
  }
}

int conn_made( int client ) {
  printf( "Connection Made...\n" );
  char *buff = malloc( 1024 );
  recv( client, buff, 1024, 0);

  int i = 0;
  for ( i = 0; i < sizeof( buff ); i++ ) {
    printf( "%d byte: %d\n", i, buff[i] );
  }
}

Upvotes: 1

Views: 2488

Answers (1)

cnicutar
cnicutar

Reputation: 182734

for ( i = 0; i < sizeof( buff ); i++ ) {
    printf( "%d byte: %d\n", i, buff[i] );
}

That sizeof is completely wrong. It will get the size of the pointer on your machine (that size is constant). You should get the number of bytes received and then print those.

Try this:

ssize_t sz;
sz = recv(client, buff, 1024, 0);
if (sz < 0) {
    perror("recv");
    return -1;
}

for (i = 0; i < sz; i++)
    printf("%d byte: %d\n", i, buff[i]);

Upvotes: 4

Related Questions