drum
drum

Reputation: 5651

Why is my ip_address[] being overwritten?

I am trying to write a server/client code and everything is working correctly, except when I am trying to store the IP addresses of incoming and outgoing connections.

getpeername(new_fd[client],(struct sockaddr*) &client_addr[client],&addr_size);
ip_address[client] = inet_ntoa(client_addr[client].sin_addr);

In this case, when a connection is established, the content of every index would be changed to the lastest connection made. So every cell of ip_address[] will contain the lastest connection's IP address. What can the problem be?

Upvotes: 1

Views: 308

Answers (2)

cnicutar
cnicutar

Reputation: 182619

inet_ntoa generally looks something like this:

char *
inet_ntoa(struct in_addr ina)
{
    static char buf[some_size];
    /* a series of sprintfs */
    return bufl
}

Which means on every call the contents of buf are going to be rewritten. Obviously you can't use the return value of inet_ntoa directly; you would have to use memcpy or something like that.

Real solution

Use inet_ntop instead. It's newer, supports IPv6 out of the box and should be thread-safe (oh yeah, inet_ntoa isn't).

Upvotes: 4

bmargulies
bmargulies

Reputation: 100013

inet_ntoa does not allocate. It returns a static buffer. You need to copy it into your own storage if you want to keep the string.

Upvotes: 2

Related Questions