问题描述
在程序中,我需要通过 TCP 套接字发送一个整数值.我为此使用了 send()
和 recv()
函数,但它们仅以字符串形式发送和接收它.
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.
send()
和 recv()
是否有其他替代方法来发送和接收整数值?
Is there any alternative for the send()
and recv()
so as to send and receive integer values?
推荐答案
send()
和 recv()
不发送字符串.他们发送字节.由您来解释有意义的字节.
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.
如果你想发送整数,你需要决定你要发送的整数大小——1字节、2字节、4字节、8字节等.你还需要决定一个编码格式.网络顺序" 描述了 Big-Endian 格式的约定.您可以使用 或
中的以下函数与网络顺序进行转换:
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);
如果你坚持在发送前使用htonl()
(host-to-network, long)和接收后使用ntohl()
(网络到主机,long),你会没事的.
If you stick to using htonl()
before sending (host-to-network, long) and ntohl()
after receiving (network-to-host, long), you'll do alright.
这篇关于在 C 中通过 TCP 发送和接收整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!