Send and receive integer value over TCP in C

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

Is there an alternative for send() and recv() to send and receive integer values?

+4
source share
3 answers

send() and recv() do not send strings. They send bytes. It is up to you to provide a byte interpretation that makes sense.

If you want to send integers, you need to decide what integer numbers you are going to send - 1 byte, 2 bytes, 4 bytes, 8 bytes, etc. You also need to decide on the encoding format . "Network Order" describes the Big-Endian formatting convention. You can convert to and from the network 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 use htonl() before sending (host network, long) and ntohl() after receiving (from network to host), you will do everything in order.

+8
source

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

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

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

You can then encode the add-on on the receiving side.

The reason for calling htonl() is that the high byte is usually transmitted first over the Internet, while some computer architectures, such as the ubiquitous x86, first store the low byte. If you do not correct the byte order, and the machine on one end is x86, and the machine on the other end is something else, then without htonl() integer will be distorted.

I am not an expert on this topic, by the way, but, in the absence of experimental answers, this answer can happen. Good luck.

+4
source

I tried it too. But writing failed. 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 
+4
source

All Articles