如何通过套接字发送整数?
我正在尝试通过套接字发送一个整数。我正在使用这段代码来做到这一点;但是,我的 C 代码无法编译。编译器抱怨 myInt 尚未声明。
int tmp = htonl(myInt);
write(socket, &tmp, sizeof(tmp));
如何声明 myInt?谢谢。
I am trying to send an integer through a socket. I am using this code to do so; however, my C code will not compile. The compiler complains that myInt has not been declared.
int tmp = htonl(myInt);
write(socket, &tmp, sizeof(tmp));
How do I declare myInt? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您确定它已在您的程序中正确声明了吗?
尝试这样:
Are you sure that it was properly declared in your program ?
Try like this:
在处理套接字库之前,您可能需要花一些时间学习基本的 C 语言。
您需要将 myInt 声明为整数类型的变量,如下所示:
这向编译器引入了一个名为“myInt”的标识符,其类型为 int。然后,编译器可以根据 myInt 的类型来决定您是否正在使用 myInt 进行合法的操作。
为变量赋予初始值几乎总是一个好主意:
You may need to just spend some time learning basic C before tackling the sockets library.
You need to declare myInt as a variable of type integer as follows:
This introduces the compiler to an identifier called "myInt" whose type is int. The compiler can then make decisions as to whether you're doing legal things with myInt based on its type.
Its almost always a good idea to also give the variable an initial value:
一种简单的解决方案是将整数类型化为 char 并发送 char 缓冲区的 4 个字节
int myInt
char * ptr = &myInt;
写(套接字,ptr,sizeof(int));
在接收端读取4个字节..
你不会对字节顺序有任何问题。
One simple solution is typecase the integer to char and send 4bytes of the char buffer
int myInt
char * ptr = &myInt;
write(socket, ptr, sizeof(int));
at the recieving end read the 4bytes..
u wont have any problem with the endianess.
将所有内容转换为
char
,您不必担心字节顺序,因为char
是一个字节,而是逐个字节地读取它。Convert everything to
char
, you won't have to worry about endianness because achar
is a byte, read it byte for byte instead.