How to send IPV6 multicast message in LAN?

Hi,

I want to send message to ipv6 multicast group, use the code as below.

It works on my macbook and ios simulators, but failed on the iphone or ipad device and print the log "sendto: Can't assign requested address".

Could anybody help ?


void sendIPV6Multicast(void)
{
    struct sockaddr_in6 sin = {0};
    char smsg[] = {"abcdef"}; 
    int wifiInterface;
    int fd;
    long ret;

    fd = socket(AF_INET6, SOCK_DGRAM, 0);
    if (fd < 0)
        perror("socket");

    wifiInterface = if_nametoindex("en0");

    if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &wifiInterface, sizeof(wifiInterface)) < 0)
        perror("setsockopt");

    inet_pton(AF_INET6, "FF12::99", &sin.sin6_addr);
    sin.sin6_family = AF_INET6;
    sin.sin6_scope_id = wifiInterface;
    sin.sin6_port = htons(6000);

    ret = sendto(fd, smsg, strlen(smsg), 0, (struct sockaddr*)&sin, sizeof(sin));
    if (ret < 0)
        perror("sendto");
}

Replies

I'm up against the same issue. I'm currently digesting the thread here:


https://forums.developer.apple.com/thread/21728

Any luck with the solution? I am struggling with the same issue

Here’s the code I used for sending IPv6 multicasts:

destinationAddress = [self destinationAddress];

sock = socket(destinationAddress.ss_family, SOCK_DGRAM, 0);
success = (sock >= 0);
if ( ! success ) {
    [self reportErrorWithContext:@"socket" error:errno];
}

if (success) {
    success = [self configureSocket:sock];
}

if (success) {
    bytesSent = sendto(sock, dataToSend.bytes, dataToSend.length, 0, (struct sockaddr *) &destinationAddress, destinationAddress.ss_len);
    if (bytesSent < 0) {
        [self reportErrorWithContext:@"sendto" error:errno];
    } else if ( (size_t) bytesSent != dataToSend.length) {
        [self reportErrorWithContext:[NSString stringWithFormat:@"short %zd", bytesSent] error:EAGAIN];
    } else {
        [self.delegate UDPCasterDidSendData:self];
    }
}

Where the internals of

-destinationAddress
look like tihs:
struct sockaddr_in6 * addrPtr = (struct sockaddr_in6 *) &destinationAddress;
addrPtr->sin6_family = AF_INET6;
addrPtr->sin6_len    = sizeof(*addrPtr);
addrPtr->sin6_port   = htons(12347);
addrPtr->sin6_scope_id = self.interfaceIndex;
success = inet_pton(AF_INET6, "FF02::12", &addrPtr->sin6_addr) == 1;
assert(success);

and the internals of

-configureSocket:
look like this:
success = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, &interfaceIndex, sizeof(interfaceIndex)) == 0;
if ( ! success ) {
    [self reportErrorWithContext:@"setsockopt/IPV6_MULTICAST_IF" error:errno];
}

I just rebuilt and ran my testing project for this and it continues to work as expected on iOS 11.1.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"