开发者

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

开发者 https://www.devze.com 2023-02-12 19:12 出处:网络
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 */

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


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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消