4

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?

ЯegDwight
  • 24,821
  • 10
  • 45
  • 52
James Joy
  • 176
  • 2
  • 4
  • 11

3 Answers3

10

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.

sarnold
  • 102,305
  • 22
  • 181
  • 238
5

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.

thb
  • 13,796
  • 3
  • 40
  • 68
4

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