未在 iOS UDP 套接字中获取数据回调

Not getting data callbacks in iOS UDP socket

我正在尝试在 iOS 上设置 UDP 套接字以侦听通过多播套接字发送的数据报:

#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);
    }
}

所有套接字调用都成功,但我没有收到任何回调(我正在从单独的 macOS 应用程序向 MC 地址发送 UDP 数据报)。

我做错了什么?

感谢您的所有帮助! 干杯。

问题是 CFSocket 本身不能接收发送到 IPv4(或 IPv6)多播地址的数据报。但并非一切都没有希望!

https://justanapplication.wordpress.com/category/posix/posix-system-calls/posix-socket/ 我发现了这个:"Fortunately the function CFSocketCreateWithNative can turn a theoretical POSIX socket into a theoretical CFSocket." 这个的作者 Simon Lewis 也说这实际上也有效,"at least on an iPad running iOS 7.0.4," 他很好地提供了一些尝试使用的代码。祝你好运!