Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending floating point number from server to client

I am using TCP/IP socket programming. I have a floating point value stored in a variable ret_val in my server code which I want to send to the client which is waiting to receive it.

How can I do it?

like image 921
Biswajyoti Das Avatar asked Dec 05 '25 17:12

Biswajyoti Das


2 Answers

If you know that both client and server are the same platform etc., you can simply use sizeof(float) to determine your buffer size and copy that many bytes from the address of your float.

float number = 123.45;
send(sockfd, &number, sizeof(float),0);

As soon as your client/server are different platforms/different languages etc. you'll have to start worrying about how to portably encode the float. But for a simple approach, the above will work fine.

like image 108
Brian Agnew Avatar answered Dec 08 '25 10:12

Brian Agnew


float f = ...;
size_t float_size = sizeof(float);
const char* buffer = (const char *) &f;
send(mySocket, buffer, float_size, 0);

This code will work fine if both the server and client use the same platform. If the platforms are different, you will have to negotiate message sizes and endianess explicitly.

like image 30
Sergii Volchkov Avatar answered Dec 08 '25 09:12

Sergii Volchkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!