发送和下在TCP接收一个整数值 [英] Send and receive an integer value over TCP in C

查看:246
本文介绍了发送和下在TCP接收一个整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个程序,我需要通过TCP套接字发送一个整数值。我使用了发送()为宗旨的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.

是否有任何替代的发送()的recv(),以发送和接收整数?

Is there any alternative for the send() and recv() so as to send and receive integer values?

推荐答案

发送()的recv()不发送字符串。他们发送的字节的。它是由您提供有意义的字节间pretation。

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字节等还需要上的encoding~~V格式网络命令介绍大端格式的约定。您可以使用以下功能转换和从网络顺序从< ARPA / inet.h> < netinet / in.h中>

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()发送(主机到网络长)之前和 ntohl()接收(网络到主机,长)后,你会做没事的。

If you stick to using htonl() before sending (host-to-network, long) and ntohl() after receiving (network-to-host, long), you'll do alright.

这篇关于发送和下在TCP接收一个整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆