Reputation: 3189
Here is the code I am trying to setup for some time now, I can't figure out why this is not working. I create a simple function with a sockaddr_in in input. I want it to return (without print) a char* containing the IP associated to the sockaddr_in.
char* get_ip_from_sockaddr(struct sockaddr_in client_addr)
{
int a = (client_addr.sin_addr.s_addr&0xFF);
int b = (client_addr.sin_addr.s_addr&0xFF00)>>8;
int c = (client_addr.sin_addr.s_addr&0xFF0000)>>16;
int d = (client_addr.sin_addr.s_addr&0xFF000000)>>24;
char* ip[24];
int n = sprintf(ip, "%d.%d.%d.%d", a, b, c, d);
printf("%s", ip); // The IP is correctly printed
return ip;
}
I retrieve the ip like this:
char* ip = get_ip_from_sockaddr(client_addr);
printf("IP CLIENT: %s\n", ip);
Here is the output of my programm:
127.0.0.1IP CLIENT: �����
I don't understand why this is correctly printed inside the function but when I retrieve from the function the IP is not printed.
Upvotes: 1
Views: 905
Reputation: 496
You have declared ip as an array of pointers, not a char array. But more fundamentally, it's a local array which lives on the stack, and when you return from the function, the memory is released and could be overwritten with anything.
If you declare ip as
static char ip[24];
, you should be safe. With one caveat: all calls to the function will use the same memory for the ip string, so the result of one call will be overwritten by the next call.
Upvotes: 3