0

我正在尝试获取连接到服务器套接字的客户端 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";
};
4

2 回答 2

3

addressLength打电话之前忘记设置了getpeername。你需要:

addressLength = sizeof(address);

正如文档所说:

如果提供的缓冲区太小,返回的地址将被截断

于 2012-08-16T20:27:07.263 回答
2

您需要将完整sockaddr_in实例传递给getpeername()而不是sockaddr实例,并且需要addressLength在调用之前设置getpeername()

void SocketServer::Log ( int socketFD , string message )       
{       
    struct sockaddr_in                  address = {0};       
    socklen_t                           addressLength = sizeof(address);       
    string                              ip;       
    int                                 port;       

    int result = getpeername ( socketFD , (struct sockaddr*) &address , &addressLength );       
    cout << "Address length is " << addressLength << "     Return is " <<  result << endl;       

    ip = inet_ntoa ( address.sin_addr );       
    port = ntohs ( address.sin_port );       

    cout << "Socket FD is " << socketFD << " " << ip << ":" << port << " " <<  message << endl;       
}; 
于 2012-08-16T20:33:37.517 回答