如何检索请求连接到我的服务器的对等客户端的 IP 地址和主机名。客户端和服务器都连接在不同的网络中
我尝试了 getpeername() ..但是当客户端和服务器都连接在同一网络中时,它会提供正确的 IP 地址。
Socket* SocketServer::Accept()
{
struct sockaddr_in cli_addr;
struct hostent *hp;
int clilen = 0;
clilen = sizeof (cli_addr);
SOCKET new_sock = accept(s_, (struct sockaddr *) &cli_addr, &clilen);
if (new_sock == INVALID_SOCKET)
{
SetLastError( WSAGetLastError() );
// std::cout<<"Socket invalid due to :"<<WSAGetLastError()<<endl;
WSACleanup();
}
Socket* r = new Socket(new_sock);
//std::cout<<" Accepted Connection"<<endl;
int ret = getpeername(new_sock, (struct sockaddr *)&cli_addr, &clilen);
struct sockaddr_in *s = (struct sockaddr_in *)&cli_addr;
std::string ip = inet_ntoa(cli_addr.sin_addr);
//cout << " The IP address from the accept is " << ip << std::endl;
hp = gethostbyaddr((char *)&cli_addr.sin_addr,sizeof(cli_addr.sin_addr),AF_INET);
std::string cliname;
if (hp!=NULL)
cliname = hp->h_name;
r->setDNS(cliname);
r->setIP(ip);
return r;
}