THRIFT-1944: Binding to zero port
Client: cpp
Patch: Akshat Aranya
diff --git a/lib/cpp/src/thrift/transport/TServerSocket.cpp b/lib/cpp/src/thrift/transport/TServerSocket.cpp
index 59a0885..1df719d 100755
--- a/lib/cpp/src/thrift/transport/TServerSocket.cpp
+++ b/lib/cpp/src/thrift/transport/TServerSocket.cpp
@@ -337,6 +337,29 @@
 
     // free addrinfo
     freeaddrinfo(res0);
+
+    // retrieve bind info
+    if (port_ == 0 && retries <= retryLimit_) {
+      struct sockaddr sa;
+      socklen_t len = sizeof(sa);
+      std::memset(&sa, 0, len);
+      if (::getsockname(serverSocket_, &sa, &len) < 0) {
+        int errno_copy = errno;
+        GlobalOutput.perror("TServerSocket::getPort() getsockname() ", errno_copy);
+      }
+      else {
+        if (sa.sa_family == AF_INET6) {
+          const struct sockaddr_in6*
+            sin = reinterpret_cast<const struct sockaddr_in6 *>(&sa);
+          port_ = ntohs(sin->sin6_port);
+        }
+        else {
+          const struct sockaddr_in*
+            sin = reinterpret_cast<const struct sockaddr_in *>(&sa);
+          port_ = ntohs(sin->sin_port);
+        }
+      }
+    }
   }
 
   // throw an error if we failed to bind properly
@@ -365,6 +388,10 @@
   // The socket is now listening!
 }
 
+int TServerSocket::getPort() {
+    return port_;
+}
+
 shared_ptr<TTransport> TServerSocket::acceptImpl() {
   if (serverSocket_ == THRIFT_INVALID_SOCKET) {
     throw TTransportException(TTransportException::NOT_OPEN, "TServerSocket not listening");
diff --git a/lib/cpp/src/thrift/transport/TServerSocket.h b/lib/cpp/src/thrift/transport/TServerSocket.h
index 4a8c029..e7b7a82 100644
--- a/lib/cpp/src/thrift/transport/TServerSocket.h
+++ b/lib/cpp/src/thrift/transport/TServerSocket.h
@@ -59,6 +59,7 @@
   void close();
 
   void interrupt();
+  int getPort();
 
  protected:
   boost::shared_ptr<TTransport> acceptImpl();