0

I just like to ask if it is possible to identify the IP Address of a device (e.g. a printer) using its Hostname even if its Bonjour setting is turned off? Also can you give me an example on how to do it? I am developing an app in iOS that should handle this scenario.

I have looked at the following:

  1. getaddrinfo
  2. CFHostStartInfoResolution

but they work only if the device's bonjour is turned ON.

MiuMiu
  • 1,905
  • 2
  • 19
  • 28
  • 1
    `nameOfTheDevice.local` should work, at least this works for my iPhone and SSH. –  Sep 21 '12 at 07:43
  • `nameOfTheDevice.local` only works for me when bonjour (of the device with hostname `nameOfTheDevice`) is turned ON. – MiuMiu Sep 21 '12 at 08:27

2 Answers2

0

Assuming the hostname (let's say nameOfTheDevice) is registered with the zone's authoritative DNS server, you can use CFHost to look up an address or hostname. For example:

NSString* hostname = @"nameOfTheDevice";
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);

Boolean lookup = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL);
NSArray* addresses = (NSArray*)CFHostGetAddressing(hostRef, &lookup);

[addresses enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *strDNS = [NSString stringWithUTF8String:inet_ntoa(*((struct in_addr *)obj))];
       NSLog(@"Resolved %d->%@", idx, strDNS);
  }];

(Remember to put error checks in your production code). Bear in mind that if the DNS server isn't aware of that hostname, there's nothing you can do. It's not safe to assume that you'll be able to perform a successful lookup, especially on a home network where built-in DHCP/DNS servers have widely varying capabilities.

Chris Mowforth
  • 6,689
  • 2
  • 26
  • 36
0

From previous answer get callback func and pass obj as a parameter into this function

void printAddr(CFDataRef address)
{
    NSString *addressString;
    struct sockaddr *addressGeneric;

NSData *myData = (__bridge NSData*)address;
addressGeneric = (struct sockaddr*)[myData bytes];

switch(addressGeneric->sa_family) {
    case AF_INET: {
      struct sockaddr_in *ip4;
      char dest[INET_ADDRSTRLEN];
      ip4 = (struct sockaddr_in *) [myData bytes];
      addressString = [NSString stringWithFormat: @"IP4: %s", inet_ntop(AF_INET, &ip4->sin_addr, dest, sizeof dest)];
     }
     break;

    case AF_INET6: {
        struct sockaddr_in6 *ip6;
        char dest[INET6_ADDRSTRLEN];
        ip6 = (struct sockaddr_in6 *) [myData bytes];
        addressString = [NSString stringWithFormat: @"IP6: %s",  inet_ntop(AF_INET6, &ip6->sin6_addr, dest, sizeof dest)];
     }
     break;
 }

NSLog(@"%@", addressString);
}
Kirill Belonogov
  • 414
  • 4
  • 14