我正在尝试获取连接到服务器套接字的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";
};
答案 0 :(得分:2)
在致电addressLength
之前,您忘了设置getpeername
。你需要:
addressLength = sizeof(address);
正如文件所说:
如果提供的缓冲区太小,则会截断返回的地址
答案 1 :(得分: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;
};