简体   繁体   English

获取在不同网络中连接的远程客户端的主机名和IP地址

[英]Get hostname and IP address of the remote client connected in a different network

How do I retrieve IP address and hostname of the peer client requesting connection to my server.Both client and Server are connected in different networks 如何检索请求连接到我的服务器的对等客户端的IP地址和主机名。客户端和服务器都连接在不同的网络中

I tried getpeername()..But it gives the right IP address when both client and server are connected in same network. 我尝试了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;
}

If I read your question correctly, the client is behind a NAT box that rewrites the source IP address and you want the original one. 如果我正确地读了你的问题,那么客户端就在一个NAT盒子后面,它重写了源IP地址而你想要原始IP地址。 If that is the case, there's nothing you can do to find out "the real" IP address, short of asking the client to send it to you. 如果是这种情况,那么你无法找到“真正的”IP地址,除非要求客户将其发送给你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM