@@ -281,14 +281,32 @@ void SetCommandLine() {
281
281
#endif
282
282
}
283
283
284
+ /* ******************************************************************************
285
+ * Utility function to format socket information.
286
+ *******************************************************************************/
287
+ void reportEndpoint (uv_handle_t * h, struct sockaddr * addr, const char * prefix,
288
+ std::ostringstream& out) {
289
+ uv_getnameinfo_t endpoint;
290
+ if (uv_getnameinfo (h->loop , &endpoint, nullptr , addr, NI_NUMERICSERV) == 0 ) {
291
+ out << prefix << endpoint.host << " :" << endpoint.service ;
292
+ } else {
293
+ char host[INET6_ADDRSTRLEN];
294
+ int family = addr->sa_family ;
295
+ if (uv_inet_ntop (family, addr, host, sizeof (host)) == 0 ) {
296
+ std::string port = std::to_string (ntohs (family == AF_INET ?
297
+ reinterpret_cast <sockaddr_in*>(addr)->sin_port :
298
+ reinterpret_cast <sockaddr_in6*>(addr)->sin6_port ));
299
+ out << prefix << host << " :" << port;
300
+ }
301
+ }
302
+ }
303
+
284
304
/* ******************************************************************************
285
305
* Utility function to format libuv socket information.
286
306
*******************************************************************************/
287
307
void reportEndpoints (uv_handle_t * h, std::ostringstream& out) {
288
308
struct sockaddr_storage addr_storage;
289
309
struct sockaddr * addr = (sockaddr*)&addr_storage;
290
- char hostbuf[NI_MAXHOST];
291
- char portbuf[NI_MAXSERV];
292
310
uv_any_handle* handle = (uv_any_handle*)h;
293
311
int addr_size = sizeof (addr_storage);
294
312
int rc = -1 ;
@@ -305,23 +323,13 @@ void reportEndpoints(uv_handle_t* h, std::ostringstream& out) {
305
323
default : break ;
306
324
}
307
325
if (rc == 0 ) {
308
- // getnameinfo will format host and port and handle IPv4/IPv6.
309
- rc = getnameinfo (addr, addr_size, hostbuf, sizeof (hostbuf), portbuf,
310
- sizeof (portbuf), NI_NUMERICSERV);
311
- if (rc == 0 ) {
312
- out << std::string (hostbuf) << " :" << std::string (portbuf);
313
- }
326
+ reportEndpoint (h, addr, " " , out);
314
327
315
328
if (h->type == UV_TCP) {
316
329
// Get the remote end of the connection.
317
330
rc = uv_tcp_getpeername (&(handle->tcp ), addr, &addr_size);
318
331
if (rc == 0 ) {
319
- rc = getnameinfo (addr, addr_size, hostbuf, sizeof (hostbuf), portbuf,
320
- sizeof (portbuf), NI_NUMERICSERV);
321
- if (rc == 0 ) {
322
- out << " connected to " ;
323
- out << std::string (hostbuf) << " :" << std::string (portbuf);
324
- }
332
+ reportEndpoint (h, addr, " connected to " , out);
325
333
} else if (rc == UV_ENOTCONN) {
326
334
out << " (not connected)" ;
327
335
}
0 commit comments