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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With