2

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?

1
  • 2
    It might be helpful if you specify the language and / or runtime that is being used by the sender and receiver. Commented Jul 31, 2009 at 11:52

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@BrianAgnew Sorry dumb question here, what do you mean, that both the client and the server are on the same platform?
Processor type? 32 vs 64 bit etc
5
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.

Comments

3

Use a textual representation ?

char buf[32] ; 
snprintf(buf,sizeof buf,"%f",ret_val); 
write(fd,buf,strlen(buf));

You can read that string and parse it back again with sscanf. (Maybe even make it line terminated - "%f\n" - so you'll know when the number ends.)

The direct approach is to simply

write(fd,&ret_val,sizeof ret_val);

In both cases you should check the return value of write and take proper action if an error occurs, or write() wrote less bytes than you told it to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.