Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send and receive an integer value over TCP in C

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?

like image 917
James Joy Avatar asked Dec 02 '22 22:12

James Joy


1 Answers

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.

like image 109
sarnold Avatar answered Dec 11 '22 11:12

sarnold