@@ -214,6 +214,7 @@ - (id) _initWithKey: (NSString*)key
214214 for (tmp = entry; tmp != NULL ; tmp = tmp->ai_next )
215215 {
216216 char ipstr[INET6_ADDRSTRLEN];
217+ char host[NI_MAXHOST];
217218 void *addr;
218219
219220#pragma clang diagnostic push
@@ -236,9 +237,22 @@ - (id) _initWithKey: (NSString*)key
236237 inet_ntop (tmp->ai_family , addr, ipstr, sizeof (ipstr));
237238 [addresses addObject: [NSString stringWithUTF8String: ipstr]];
238239
240+ /* Possibly a reverse lookup of the address will give us a different
241+ * result to our key (if the key was an address or an alias) so we
242+ * might be able to get a new name for the host.
243+ */
244+ if (getnameinfo (tmp->ai_addr , tmp->ai_addrlen , host, sizeof (host),
245+ NULL , 0 , NI_NAMEREQD) == 0 )
246+ {
247+ [names addObject: [NSString stringWithUTF8String: host]];
248+ }
249+
250+ /* If we have a conaonical name for the host, use it.
251+ */
239252 if (tmp->ai_canonname && *tmp->ai_canonname )
240253 {
241254 unsigned char response[NS_PACKETSZ];
255+ extern int h_errno;
242256 ns_msg msg;
243257 int count;
244258 int len;
@@ -248,13 +262,17 @@ - (id) _initWithKey: (NSString*)key
248262 n = [NSString stringWithUTF8String: tmp->ai_canonname];
249263 [names addObject: n];
250264
251- /* Perform DNS query for CNAME record (type CNAME = 5)
265+ /* Perform DNS query for CNAME records so that we can get
266+ * any name pointed to by this one.
252267 */
253268 len = res_query (tmp->ai_canonname , ns_c_in, ns_t_cname,
254269 response, sizeof (response));
255270 if (len < 0 )
256271 {
257- perror (" res_query" );
272+ if (h_errno != NO_DATA)
273+ {
274+ herror (" res_query" );
275+ }
258276 continue ;
259277 }
260278
@@ -284,6 +302,12 @@ - (id) _initWithKey: (NSString*)key
284302 }
285303 if (entry)
286304 {
305+ if (nil == [addresses member: key])
306+ {
307+ /* The key was not an address ... so it must be a host name
308+ */
309+ [names addObject: key];
310+ }
287311 freeaddrinfo (entry);
288312 }
289313 if ([names count ] || [addresses count ])
@@ -438,6 +462,12 @@ + (void) initialize
438462 [[NSObject leakAt: &_hostCacheLock] release ];
439463 _hostCache = [NSMutableDictionary new ];
440464 [[NSObject leakAt: &_hostCache] release ];
465+ #if defined(HAVE_GETADDRINFO) && defined(HAVE_RESOLV_H)
466+ if (res_init () < 0 )
467+ {
468+ NSLog (@" +[NSHost initialize] error in res_init()" );
469+ }
470+ #endif
441471 }
442472}
443473
0 commit comments