我正在尝试获取连接到服务器套接字的客户端 IP 和端口。我传递了以下函数客户端套接字文件描述符,但它返回 0.0.0.0:0 这让我发疯,但有时它返回类似 248.127.0.0:24870 的东西......我做错了什么?
PS返回地址长度为16,函数返回结果为0,无错误。
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";
};