简体   繁体   中英

Not getting data callbacks in iOS UDP socket

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM