简体   繁体   中英

how to read more than 256 bytes over a socket in C

I am facing the problem that my server is sending a string which is of size 600 bytes. Now for reading from the server my client uses the statement

   n=read(sockfd,rbuffer,255);

where rbuffer is my buffer.

If i try to increase the size mentioned in the read statement (255) i'm getting a segmentation fault.

Now that I know that the client is receiving only the partial information sent by the server.How can I modify or change the way I read the information so that I can read all of the bytes?

PS: the size of the string is so big since I am trying to send an XML string across.

You need to also increase the size of rbuffer . One way to do that could be:

unsigned char rbuffer[4096];
n = read(socksfd, rbuffer, sizeof(rbuffer));

That way if you decide to change the size you only have to do it in one place.

Well, when you look at the read() system call documentation, it says that the last argument is the size of your buffer.

In your case, you'll want to make sure that rbuffer is large enough!

I guess you have somewhere:

unsigned char rbuffer[255];
n = read( sockfd, rbuffer, 255);

You'll want to do that:

unsigned char rbuffer[1024];
n = read( sockfd, rbuffer, 1024);

To be sure not to put an invalid value as the size, use sizeof( rbuffer ) if it is allocated on the stack (like above).

If it is dynamically allocated, you'll have to use the size you used when allocating the buffer:

int bufsize = 1024;
char *buffer = malloc(bufsize);
n = read( sockfd, buffer, bufsize);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM