Send and receive an integer value over TCP in C

24,049

Solution 1

send() and recv() don't send strings. They send bytes. It is up to you to provide an interpretation of the bytes that makes sense.

If you wish to send integers, you need to decide what size integers you are going to send -- 1 byte, 2 bytes, 4 bytes, 8 bytes, etc. You also need to decide on an encoding format. "Network order" describes the convention of Big-Endian formatting. You can convert to and from network order using the following functions from <arpa/inet.h> or <netinet/in.h>:

   uint32_t htonl(uint32_t hostlong);
   uint16_t htons(uint16_t hostshort);
   uint32_t ntohl(uint32_t netlong);
   uint16_t ntohs(uint16_t netshort);

If you stick to using htonl() before sending (host-to-network, long) and ntohl() after receiving (network-to-host, long), you'll do alright.

Solution 2

You can send the integer as four bytes, of course (or however many bytes your integer happens to be); but you have to be careful. See the function htonl(), presented on your system probably in <arpa/inet.h>.

Assuming a four-byte integer n, this might do what you want:

uint32_t un = htonl(n);
send(sockfd, &un, sizeof(uint32_t), flags);

Then you can code the complement on the receiving end.

The reason for the call to htonl() is that the highest-order byte is conventionally transmitted first over the Internet, whereas some computer architectures like the ubiquitous x86 store the lowest-order byte first. If you don't fix the byte order, and the machine on one end is an x86, and the machine on the other end is something else, then without the htonl() the integer will come through garbled.

I am not an expert on the topic, incidentally, but in the absence of experter answers, this answer might serve. Good luck.

Solution 3

I tried it, too. But write didn't work. So I found another solution.

// send
char integer[4];                  // buffer
*((int*)integer) = 73232;         // 73232 is data which I want to send.
send( cs, integer, 4, 0 );        // send it

// receive
char integer[4];                  // buffer
recv( s, integer, 4, 0 );         // receive it
Share:
24,049
James Joy
Author by

James Joy

Updated on June 29, 2020

Comments

  • James Joy
    James Joy almost 4 years

    In a program, I need to send an integer value over the TCP socket. I used the send() and recv() functions for the purpose but they are sending and receiving it only as string.

    Is there any alternative for the send() and recv() so as to send and receive integer values?

  • Jayapal Chandran
    Jayapal Chandran over 7 years
    It works for me when i tried now. I wonder why we did not prefix the ampersand for the second argument. any idea?
  • Jayapal Chandran
    Jayapal Chandran over 7 years
    That works as expected in cross compilation and in a mixed compilation environment.
  • EsmaeelE
    EsmaeelE over 6 years
    How do you print integer in receive side? it must be same as 73232