CFSocket Callback not working....Please Help Me

Discussion in 'Mac Programming' started by likenoother, Oct 1, 2008.

  1. likenoother macrumors newbie

    Oct 1, 2008
    I am trying to receive broadcast on UDP. I have tried everything possible but i dont receive any callback. but i see the socket open on lsof. it shows my socket with the port number 15598. but for some reason dealWithData does not get called. am i missing something here i am very new to CFsockets. Please help

    static void dealWithData(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info)
    printf("received %d bytes from socket %d\n", CFDataGetLength((CFDataRef)data), CFSocketGetNative(s));

    static void receiveData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info)
    // CFSocketSendData(socket, address, (CFDataRef)data, 0.0);
    printf("Hello World");

    static void SetSocketBlockingEnabled(int sock, bool blocking)
    int flags = fcntl(sock, F_GETFL, 0);
    flags = blocking ? (flags&~O_NONBLOCK) : (flags|O_NONBLOCK);
    fcntl(sock, F_SETFL, flags);

    -(void) searchHosts
    CFSocketRef searchsocket = CFSocketCreate(kCFAllocatorDefault, AF_INET, SOCK_DGRAM, IPPROTO_UDP, kCFSocketDataCallBack, (CFSocketCallBack)&dealWithData, NULL);
    int fd = -1;
    if ( searchsocket == NULL) {
    NSLog(@"CfSocketCreate Failed");
    if( searchsocket ) {
    fd = CFSocketGetNative(searchsocket);
    if (fd == -1) {

    NSLog(@"CfSocketGetnative Failed");}
    int yes = 1;
    setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (void *)&yes, sizeof(yes));
    //SetSocketBlockingEnabled(fd, true);

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_len = sizeof(addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(15598); //port
    //inet_aton("", &addr.sin_addr);
    //addr.sin_addr.s_addr = htonl(INADDR_ANY);

    //bind(fd, (struct sockaddr *)&addr, sizeof(addr));

    //struct sockaddr_in a = {0, AF_INET, 1234, 0};
    CFDataRef searchAddress = CFDataCreate(NULL, (UInt8 *)&addr, sizeof(struct sockaddr_in));

    CFSocketSetAddress(searchsocket, searchAddress);

    //CFSocketSetAddress(searchsocket, searchAddress);

    CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(NULL, searchsocket, 0);

    if(source == NULL)
    NSLog(@"Sorry could not created loop");

    CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);


    Please help i am really stuck here.
  2. bluegene macrumors newbie

    Dec 8, 2010
    i think you should check the return value of the function CFSocketSetAddress(searchsocket, searchAddress),ensure weather it returns success or other errors.
    if it returns error,i think the callback would not be called.


Share This Page