Not getting data callbacks in iOS UDP socket

201 views Asked by At

I'm trying to set up a UDP socket on iOS to listen for datagrams coming over a multicast socket:

#import <CoreFoundation/CoreFoundation.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void getSocketDataCallBack (CFSocketRef cfSocketRef, CFSocketCallBackType cbType, CFDataRef address, const void *data, void *info) {
    if (cbType == kCFSocketDataCallBack) {
        cout << "o";
    } else {
        cout << "x";
    }
}


void main () {
    CFSocketError cfErr;
    CFSocketContext udpSocketContext = {0, NULL, NULL, NULL, NULL};
    udpSocketContext.info = &cbData;
    CFSocketRef udpSocketRef = CFSocketCreate(kCFAllocatorDefault,
                                              PF_INET,
                                              SOCK_DGRAM,
                                              IPPROTO_UDP,
                                              kCFSocketDataCallBack,
                                              &getSocketDataCallBack,
                                              &udpSocketContext);
    if ( udpSocketRef == NULL) {
        cout << "CFSocketCreate failed\n";
    } else {
        cout << "UDP socket created\n";

        CFRunLoopSourceRef source = CFSocketCreateRunLoopSource( kCFAllocatorDefault, udpSocketRef, 0 );
        CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );

        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_len = sizeof(addr);
        addr.sin_family = AF_INET;
        addr.sin_port = htons(MC_PORT);       //4194
        inet_aton(MC_ADDR, &addr.sin_addr);   //239.0.123.45

        //Tell socket to listen on this address
        CFDataRef cfDataRef = CFDataCreate(NULL, (const UInt8 *)&addr, sizeof(addr));
        cfErr = CFSocketSetAddress(udpSocketRef, cfDataRef);
    }
}

All the socket calls succeed, but I don't get any callbacks (I am sending UDP datagrams to the MC address from a separate macOS application).

What am I doing wrong?

Thanks for any an all assistance! Cheers.

1

There are 1 answers

0
bob quinn On BEST ANSWER

The problem is that CFSocket does not in itself enable receipt of datagrams sent to an IPv4 (nor IPv6) multicast address. But all is not hopeless!

At https://justanapplication.wordpress.com/category/posix/posix-system-calls/posix-socket/ I found this: "Fortunately the function CFSocketCreateWithNative can turn a theoretical POSIX socket into a theoretical CFSocket." The author of this, Simon Lewis, also says that this actually works, too, "at least on an iPad running iOS 7.0.4," and he is nice enough to provide some code to try it out with. Good Luck!