0
0
mirror of https://github.com/zeromq/libzmq.git synced 2024-12-28 16:15:23 +08:00

Add get_peer_ip_address utility function

The functon returns string representation of peer's
IP address. We will need this to update ZAP implementation.
This commit is contained in:
Martin Hurton 2013-07-18 09:28:56 +02:00
parent 4944095262
commit 7541debe6d
2 changed files with 46 additions and 1 deletions

View File

@ -27,6 +27,7 @@
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
@ -108,3 +109,42 @@ void zmq::enable_ipv4_mapping (fd_t s_)
#endif
}
bool zmq::get_peer_ip_address (fd_t sockfd_, std::string &ip_addr_)
{
int rc;
struct sockaddr_storage ss;
#if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_WINDOWS
int addrlen = static_cast <int> (sizeof ss);
#else
socklen_t addrlen = sizeof ss;
#endif
rc = getpeername (sockfd_, (struct sockaddr*) &ss, &addrlen);
#ifdef ZMQ_HAVE_WINDOWS
if (rc == SOCKET_ERROR) {
wsa_assert (WSAGetLastError () != WSANOTINITIALISED &&
WSAGetLastError () != WSAEFAULT &&
WSAGetLastError () != WSAEINPROGRESS &&
WSAGetLastError () != WSAENOTSOCK)
return false;
}
#else
if (rc == -1) {
errno_assert (errno != EBADF &&
errno != EFAULT &&
errno != EINVAL &&
errno != ENOTCONN &&
errno != ENOTSOCK);
return false;
}
#endif
char host [NI_MAXHOST];
rc = getnameinfo ((struct sockaddr*) &ss, addrlen, host, sizeof host,
NULL, 0, NI_NUMERICHOST);
if (rc != 0)
return false;
ip_addr_ = host;
return true;
}

View File

@ -20,6 +20,7 @@
#ifndef __ZMQ_IP_HPP_INCLUDED__
#define __ZMQ_IP_HPP_INCLUDED__
#include <string>
#include "fd.hpp"
namespace zmq
@ -34,6 +35,10 @@ namespace zmq
// Enable IPv4-mapping of addresses in case it is disabled by default.
void enable_ipv4_mapping (fd_t s_);
// Returns string representation of peer's address.
// Socket sockfd_ must be connected. Returns true iff successful.
bool get_peer_ip_address (fd_t sockfd_, std::string &ip_addr_);
}
#endif
#endif