0

How can I check the real IP address of a connection from localhost? Basically I use the following function to get the address of a given remote connection.

std::string getpeerhost(int _fd) const {

  socklen_t len;
  struct sockaddr_storage addr;
  char ipstr[INET6_ADDRSTRLEN];
  //int port = -1;

  len = sizeof(addr);
  if(::getpeername(_fd, (struct sockaddr*)&addr, &len) == -1) {
    return {""};
  }

  // IP4
  if (addr.ss_family == AF_INET) {
    auto s = (struct sockaddr_in *)&addr;
    inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr));
  }   
  // IP6
  else {
    auto s = (struct sockaddr_in6 *)&addr;
    inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr));
  }   

  return std::string(ipstr);
}

The issue is getpeername might return 127.0.0.1 when the given socket file descriptor _fd is from the same host as the server. In my application, the server has to pass the client's address among other clients and certainly passing 127.0.0.1 doesn't make any sense.

Jes
  • 2,614
  • 4
  • 25
  • 45
  • If your machine has a static IP address just use that. If your machine is leased a DHCP address use the method described here. http://stackoverflow.com/a/10838854/2913685 – user2913685 Aug 22 '16 at 03:27
  • 1
    If `getpeername()` returns 127.0.0.1 that's where the connection is from. There is no other remote address. If you don't want your client addresses to read 127.0.0.1, don't let them connect to it: have them use the external IP address of the host. – user207421 Aug 22 '16 at 03:54

0 Answers0