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?
inet_ntoagenerally looks something like this:Which means on every call the contents of
bufare going to be rewritten. Obviously you can’t use the return value ofinet_ntoadirectly; you would have to usememcpyor something like that.Real solution
Use
inet_ntopinstead. It’s newer, supports IPv6 out of the box and should be thread-safe (oh yeah,inet_ntoaisn’t).