title: cfhoststartinforesolution fails. get device name from IP address on LAN
body: <p>As a part of assignment I have to scan my LAN and get the names of devices connected to wifi.  I went through apples documentation <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/ResolvingDNSHostnames.html" rel="nofollow noreferrer">this</a> and many other S.O links like <a href="https://stackoverflow.com/questions/25992989/how-to-get-the-other-devices-host-name-in-the-same-wifi">this</a>. However resolution is not happening, some error occurs. I am not a networking guy and hence most of it sounded greek to me. an almost same question has been asked <a href="https://stackoverflow.com/questions/19407309/cfhoststartinforesolution-always-fail-ubunteros">here</a>
  This is my code. I have written down the error that is occurring in comments.</p>
  
  <p>An alternate answer would be helpful too.</p>
  
  <pre><code>+ (NSArray *)hostnamesForAddress:(NSString *)address {
  // Get the host reference for the given address.
  CFStreamError streamError;
  struct addrinfo      hints;
  struct addrinfo      *result = NULL;
  memset(&amp;hints, 0, sizeof(hints));
  hints.ai_flags    = AI_NUMERICHOST;
  hints.ai_family   = PF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = 0;
  int errorStatus = getaddrinfo([address cStringUsingEncoding:NSASCIIStringEncoding], NULL, &amp;hints, &amp;result);
  if (errorStatus != 0) return nil;
  CFDataRef addressRef = CFDataCreate(NULL, (UInt8 *)result-&gt;ai_addr, result-&gt;ai_addrlen);
  if (addressRef == nil) return nil;
  freeaddrinfo(result);
  CFHostRef hostRef = CFHostCreateWithAddress(kCFAllocatorDefault, addressRef);
  if (hostRef == nil) return nil;
  CFRelease(addressRef);
  BOOL isSuccess = CFHostStartInfoResolution(hostRef, kCFHostNames, &amp;streamError);
  // always false
  if (!isSuccess){
      NSLog(@"error:%@",[self convertCFStreamErrorIntoNSError:streamError]);
      // error:Error Domain=kCFErrorDomainCFNetwork Code=2 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 2.)" UserInfo=0x1cd29190 {kCFGetAddrInfoFailureKey=8}
      return nil;
  }
  
  // Get the hostnames for the host reference.
  CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
  NSMutableArray *hostnames = [NSMutableArray array];
  for (int currentIndex = 0; currentIndex &lt; [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
      [hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
  }
  
  return hostnames[0];
  </code></pre>
  
  <p>}</p>