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.