Question

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?

client:

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

server:

int fileSize[1]; //buffer for reading value into?
read(sock,*fileSize,10);
int value = fileSize[0]; //I want to store value here
Was it helpful?

Solution

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:

Client:

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

Server:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top