bakalolo bakalolo - 1 year ago 70
C Question

read() write() integer value on client server using C

I'm currently working on an implementation of client server. I would like the client to send a single integer value i.e 23 using the write command to the server so the server can retrieve this value and store it in an integer variable for use later. This is what I've tried so far but obviously its wrong. Can anyone show me an easy way to do this?


int nread = 23; //the value I want to write to server
write(sockfd, nread, 10); //sockfd is socket to server


int fileSize[1]; //buffer for reading value into?
int value = fileSize[0]; //I want to store value here

Answer Source

First of all, write() will expect the address to whatever memory is going to be sent, so you can't just pass the number (your client code) or dereference an integer that's never been set (your server code). Also, is there any specific reason you're sending 10 bytes? That's really odd for an integer.

I'd try the following:


int nread = 23;
write(sockfd, &nread, sizeof(int)); // &nread returns the address to nread
write(sockfd, &nread, sizeof(nread)); // Alternative version always using the proper type


int value;
read(sock, &value, sizeof(int)); // &value returns the address to value
read(sock, &value, sizeof(value)); // Alternative version always using the proper type

However, keep in mind that this might have more issues, e.g. when considering a mix of little endian/big endian systems as well as systems with different lengths for int.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download