We are developing an iOS application for ipad that uses bonjour for conneting with other devices and couchbaseListener for replications with peer databases. We have observed that whenever [nsnetservice addresses] returns IPV6 address ,replication is not suuccesful.
We get the IPV4 address only when bluetooth is switched on randomly i.e 1 out of 5 times. In addition, [NSNetService addresses] returns only one address from the array. Is it possible in some way to convert IPV6 address to IPV4 address or else retrieve the IPV4 address always?
Please find the code used for converting to Ip address below.
char addressBuffer[INET6_ADDRSTRLEN];
for (NSData *data in self.addresses)
{
memset(addressBuffer, 0, INET6_ADDRSTRLEN);
typedef union {
struct sockaddr sa;
struct sockaddr_in ipv4;
struct sockaddr_in6 ipv6;
} ip_socket_address;
ip_socket_address *socketAddress = (ip_socket_address *)[data bytes];
if (socketAddress && (socketAddress->sa.sa_family == AF_INET || socketAddress->sa.sa_family == AF_INET6))
{
const char *addressStr = inet_ntop(
socketAddress->sa.sa_family,
(socketAddress->sa.sa_family == AF_INET ? (void *)&(socketAddress->ipv4.sin_addr) : (void *)&(socketAddress->ipv6.sin6_addr)),
addressBuffer,
sizeof(addressBuffer));
int port = ntohs(socketAddress->sa.sa_family == AF_INET ? socketAddress->ipv4.sin_port : socketAddress->ipv6.sin6_port);
if (addressStr && port)
{
NSLog(@"Found service at %s:%d", addressStr, port);
}
}
}
The IPv6 address itself contains the IPv4 address encoded in hexadecimal (after the ::)
Let's say you have the following IPv6 address: 2608::c0a8:1 (compact form)
This translates to the following IPv4 address: 192 (c0) . 168 (a8) . 0 (00 omitted) . 1 (01)
It may depend of the IPv6 address format but that's essentially the way to do.
If you aren't sure, you can try this converter: http://v6decode.com/#address=2608%3A%3Ac0a8%3A1