-1

I'm trying to use the DNSServiceRegister(...) function as part of the DNS_SD package, and for the "host" it requires a hostname as a string. However, it's possible to register a host by IP address, but the IP address has to be formatted in binary representation (instead of 192.168.1.23 it'd be 0x1701a8c0).

I assume I can trick the function by passing in the value 1701a8c0 directly, but nothing i've tried seems to work. strncpy doesn't return the expected value, just pasting it doesn't work, creating an NSData then an NSString doesn't work. I could write a loop that builds the char array 1 entry at a time, but there must be another way?

    struct sockaddr_in sa;
 ...
        ipBinary=[[NSData alloc] initWithBytes:&(sa.sin_addr.s_addr) length:8];
    ipBinStr=[[NSString alloc] initWithData:ipBinary encoding:NSUTF8StringEncoding];

I haven't been able to get any variation of this to work either:

        strncpy(str,(char *)&(sa.sin_addr.s_addr),8);
omniron
  • 11
  • 3
  • The reference mentions nothing about passing an IP address in binary format and tricking it will just make it crash as it will interpret the binary IP address as the address of the string probably reference an unmapped memory page. Surely the whole point of using this API is register the name? – trojanfoe Jul 30 '12 at 08:57

1 Answers1

1

To register a host by IP address, you probably have to pass the address in ASCII string representation, e.g. the string "192.168.1.23". You can use inet_ntoa() or better getnameinfo with the NI_NUMERICHOST flag to convert a struct sockaddr to a string.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • +1 This is far more likely to work than the solution the OP is attempting. – trojanfoe Jul 30 '12 at 09:18
  • Passing the ascii string didn't seem to work at all, but I will try this again. – omniron Jul 30 '12 at 16:04
  • Yeah, this definitely doesn't work. Even using the built-in command line tool with an ip address doesn't seem to work correctly. It always seems to resolve to the ip address 67.215.65.132 for ANY ip address I put it, on the command line tool, or the dnssd api. – omniron Jul 30 '12 at 17:10
  • @omniron: Which command line exactly have you tried? Perhaps that helps to understand the problem. – Martin R Jul 30 '12 at 18:30
  • dns-sd -P MyService _protocol._tcp local 9000 10.0.0.4 10.0.0.4 txtdata I solved the problem though. The "DNSServiceRegister" function isn't appropriate to register a service that only has an unresolvable IP address. You must use the "DNSServiceRegisterRecord" then "DNSServiceAddRecord" functions. I did get the procedure to work as I was trying, but the function doesn't properly handle non-ASCII data (not too surprising, but at least we know for sure). – omniron Jul 31 '12 at 17:33