@@ -281,14 +281,37 @@ 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
+ const int family = addr->sa_family ;
295
+ const void * src = family == AF_INET ?
296
+ static_cast <void *>(
297
+ &(reinterpret_cast <sockaddr_in*>(addr)->sin_addr )) :
298
+ static_cast <void *>(
299
+ &(reinterpret_cast <sockaddr_in6*>(addr)->sin6_addr ));
300
+ if (uv_inet_ntop (family, src, host, sizeof (host)) == 0 ) {
301
+ const int port = ntohs (family == AF_INET ?
302
+ reinterpret_cast <sockaddr_in*>(addr)->sin_port :
303
+ reinterpret_cast <sockaddr_in6*>(addr)->sin6_port );
304
+ out << prefix << host << " :" << port;
305
+ }
306
+ }
307
+ }
308
+
284
309
/* ******************************************************************************
285
310
* Utility function to format libuv socket information.
286
311
*******************************************************************************/
287
312
void reportEndpoints (uv_handle_t * h, std::ostringstream& out) {
288
313
struct sockaddr_storage addr_storage;
289
314
struct sockaddr * addr = (sockaddr*)&addr_storage;
290
- char hostbuf[NI_MAXHOST];
291
- char portbuf[NI_MAXSERV];
292
315
uv_any_handle* handle = (uv_any_handle*)h;
293
316
int addr_size = sizeof (addr_storage);
294
317
int rc = -1 ;
@@ -305,23 +328,13 @@ void reportEndpoints(uv_handle_t* h, std::ostringstream& out) {
305
328
default : break ;
306
329
}
307
330
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
- }
331
+ reportEndpoint (h, addr, " " , out);
314
332
315
333
if (h->type == UV_TCP) {
316
334
// Get the remote end of the connection.
317
335
rc = uv_tcp_getpeername (&(handle->tcp ), addr, &addr_size);
318
336
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
- }
337
+ reportEndpoint (h, addr, " connected to " , out);
325
338
} else if (rc == UV_ENOTCONN) {
326
339
out << " (not connected)" ;
327
340
}
0 commit comments