I’m trying to get IP and Port of client, connected to the server socket. I pass the following function client socket file descriptor, but it returns 0.0.0.0:0
This drives me crazy, but sometimes it returns something like 248.127.0.0:24870…
What am I doing wrong?
PS returned address length is 16. Result returned by function is 0. No errors occur.
void SocketServer::Log ( int socketFD , string message )
{
struct sockaddr address;
socklen_t addressLength;
struct sockaddr_in* addressInternet;
string ip;
int port;
int result = getpeername ( socketFD , &address , &addressLength );
cout << "Address length is " << addressLength << " Return is " << result << "\n";
addressInternet = (struct sockaddr_in*)&address;
ip = inet_ntoa ( addressInternet->sin_addr );
port = ntohs ( addressInternet->sin_port );
cout << "Socket FD is " << socketFD << " " << ip << ":" << port << " " << message << "\n";
};
You forgot to set
addressLengthbefore callinggetpeername. You need:As the documentation says: