From b0573486c7abf89b79d30aa4d29b0dac3d789619 Mon Sep 17 00:00:00 2001 From: Mikko Koppanen Date: Sat, 18 Feb 2012 19:48:09 +0000 Subject: [PATCH] Fixes for tcp_listener::get_address --- src/tcp_listener.cpp | 42 ++++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/tcp_listener.cpp b/src/tcp_listener.cpp index e791076e..7fc0203d 100644 --- a/src/tcp_listener.cpp +++ b/src/tcp_listener.cpp @@ -122,36 +122,30 @@ void zmq::tcp_listener_t::close () int zmq::tcp_listener_t::get_address (std::string *addr_) { - struct sockaddr sa; - char host[INET6_ADDRSTRLEN]; - char serv_info[32]; + struct sockaddr_storage ss; + char host [NI_MAXHOST]; + char serv_info [NI_MAXSERV]; int port, rc; - std::stringstream portnum; - + std::stringstream address; + // Get the details of the TCP socket - socklen_t sl = sizeof(sockaddr); - rc = getsockname (s, &sa, &sl); + socklen_t sl = sizeof (ss); + rc = getsockname (s, (struct sockaddr *) &ss, &sl); if (rc != 0) { return rc; } - - // Split the retrieval between IPv4 and v6 addresses - if ( sa.sa_family == AF_INET ) { - getnameinfo(&sa, sizeof(struct sockaddr), host, INET6_ADDRSTRLEN, serv_info, 32, NI_NUMERICHOST); - port = ntohs( ((struct sockaddr_in *)&sa)->sin_port); - portnum << port; - - // Store the address for retrieval by users using wildcards - *addr_ = std::string("tcp://") + std::string(host) + std::string(":") + portnum.str(); - } else { - getnameinfo(&sa, sizeof(struct sockaddr), host, INET6_ADDRSTRLEN, serv_info, 32, NI_NUMERICHOST); - port = ntohs( ((struct sockaddr_in6 *)&sa)->sin6_port); - portnum << port; - - // Store the address for retrieval by users using wildcards - *addr_ = std::string("tcp://[") + std::string(host) + std::string("]:") + portnum.str(); + + rc = getnameinfo ((struct sockaddr *) &ss, ss.ss_len, host, NI_MAXHOST, serv_info, NI_MAXSERV, NI_NUMERICHOST); + if (rc != 0) { + return rc; } - + + if (ss.ss_family == AF_INET) { + address << "tcp://" << host << ":" << port; + } else { + address << "tcp://[" << host << "]:" << port; + } + *addr_ = address.str (); return 0; }