如何通过C语言中的套接字发送和接收内存地址?
我想通过 C 中的套接字发送/接收内存地址。 我所拥有的是以下内容:
void *ptr = malloc(122); /* So the pointer points to some valid address */
unsigned char *socketData = NULL;
socketData = (unsigned char*)malloc(sizeof(void*));
memset(socketData, 0, sizeof(void*));
/* ??? How to get the memory address - where ptr points to - to socketData ??? */
我知道使用printf
打印指针地址的方法是使用%p
,即
printf("%p", ptr);
但这会打印例如0x0021ef1a。 我想要的只是以下内容: 0021ef1a
在接收方:如何将接收到的字节转换回 void*
?
啊:代码应该适用于 32 位系统以及 64 位系统;) 此外,代码应该使用 -Wall -Werror 进行编译......呵呵,
感谢您的帮助! 祝你周末愉快, 乔纳斯
I want to send/receive a memory address via a socket in C.
What I have is the following:
void *ptr = malloc(122); /* So the pointer points to some valid address */
unsigned char *socketData = NULL;
socketData = (unsigned char*)malloc(sizeof(void*));
memset(socketData, 0, sizeof(void*));
/* ??? How to get the memory address - where ptr points to - to socketData ??? */
I know that the way to print pointer addresses using printf
is to use %p
, i.e.
printf("%p", ptr);
But this prints for example 0x0021ef1a.
What I want is just the following: 0021ef1a
And on the receiver side: how to transform the received bytes back to a void*
?
Ah: and the code should work for 32bit as well for 64bit systems ;)
Furthermore the code should compile using -Wall -Werror.... huh
Thanks for helping!
Have a nice weekend,
jonas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要回答您的问题,您只需再次复制即可将原始数据转换回指针:
请注意,在大多数情况下,通过套接字发送指针没有什么意义。指针值对于接收者来说是无用的,除非它恰好是与发送者相同的进程。每个进程都会有一个单独的虚拟地址空间。
鉴于您提出的应用程序,我建议在接收方,您应该考虑用指针来表示它,因为它在这种形式下没有用处。相反,为什么不将其存储在适当大的整数类型中呢?
To answer your question, you can convert the raw data back to a pointer simply by copying again:
Note that in most situations, sending a pointer over sockets makes little sense. The pointer value will be useless to the receiver, unless it happens to be the very same process as the sender. Each process will have a separate virtual address space.
Given your proposed application, I would suggest that on the receiver side, you should consider representing this with a pointer at all, as it will be of no use in that form. Instead, why not store it in a suitably-large integer type?
如果您希望像
printf()
那样格式化指针,以发送到另一个主机进行显示,那么sprintf()
可能是正确的方法:这会创建一个固定的length 字符串,可以在远程主机上处理。这样做的优点是不需要接收主机知道发送主机的指针大小和格式的详细信息。
If you wish to format a pointer as
printf()
does, to send to another host for display, thensprintf()
may be the correct approach:This creates a fixed-length string, which can be handled on the remote host as such. The advantage of this is that it does not require the receiving host to know the details of the sending host's pointer size and format.