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

时间:2017-09-18 16:56:05

标签: ios objective-c sockets cfsocket

我试图在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);
    }
}

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

我做错了什么?

感谢所有人的帮助! 欢呼声。

1 个答案:

答案 0 :(得分:0)

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

https://justanapplication.wordpress.com/category/posix/posix-system-calls/posix-socket/我发现了这一点:&#34;幸运的是,函数CFSocketCreateWithNative可以将理论上的POSIX套接字转换为理论上的CFSocket。&#34;这个作者Simon Lewis也说,这实际上也有效,至少在运行iOS 7.0.4的iPad上,#34;并且他足够好提供一些代码来试用它。祝你好运!