简体   繁体   English

如何通过C中的套接字发送和接收内存地址?

[英]How to send and receive memory addresses via a socket in C?

I want to send/receive a memory address via a socket in C. What I have is the following: 我想通过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 ??? */

I know that the way to print pointer addresses using printf is to use %p , ie 我知道使用printf打印指针地址的方法是使用%p ,即

printf("%p", ptr);

But this prints for example 0x0021ef1a. 但这会打印例如0x0021ef1a。 What I want is just the following: 0021ef1a 我想要的只是以下内容:0021ef1a

And on the receiver side: how to transform the received bytes back to a void* ? 在接收方:如何将接收到的字节转换回void*

Ah: and the code should work for 32bit as well for 64bit systems ;) Furthermore the code should compile using -Wall -Werror.... huh 嗯:代码对于32位系统也应该适用于32位;)此外,代码应使用-Wall -Werror进行编译。

Thanks for helping! 感谢您的帮助! Have a nice weekend, jonas 乔纳斯,周末愉快

To answer your question, you can convert the raw data back to a pointer simply by copying again: 要回答您的问题,您可以简单地通过再次复制将原始数据转换回指针:

void *ptr = malloc(42);
void *ptr2 = NULL;

unsigned char *data = malloc(sizeof(void *));

memcpy(data, &ptr, sizeof(void *));

...

memcpy(&ptr2, data, sizeof(void *));

printf("ptr  = %p\n", ptr);
printf("ptr2 = %p\n", ptr2);

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? 相反,为什么不将其存储为适当大的整数类型呢?

If you wish to format a pointer as printf() does, to send to another host for display, then sprintf() may be the correct approach: 如果您希望像printf()一样格式化指针,然后发送到另一个主机进行显示,则sprintf()可能是正确的方法:

char dest[100] = "";
snprintf(dest, sizeof dest, "%p", ptr);

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. 这样做的好处是它不需要接收主机知道发送主机的指针大小和格式的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM