views:

36

answers:

1

Running on the iPhone simulator, I am listening on a port for packets, but my callback never gets called (and the packets are being sent for sure, checked with wireshark). Simplified code follows:

#define IN_PORT  (51112)

static void ReadCallback (CFSocketRef theSocket, CFSocketCallBackType theType, CFDataRef theAddress, const void *data, void *info) 
{
    NSLog(@"Data received");
}

@implementation MyListener
- (void) ListenOnPort:(uint16_t)port withCallback:(CFSocketCallBack)callback 
{
    CFSocketContext context = {0,self,NULL,NULL,NULL};
    CFSocketRef cfSocket = CFSocketCreate(NULL, PF_INET, SOCK_DGRAM, PPROTO_UDP, kCFSocketReadCallBack, callback, &context);
    if (cfSocket==NULL)
        NSLog(@"CFSocketCreate failed");

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

    NSData *address = [NSData dataWithBytes:&addr length:sizeof(addr)];
    if(kCFSocketSuccess != CFSocketSetAddress(cfSocket, (CFDataRef)address))
        NSLog(@"CFSocketSetAddress failed");

    CFRunLoopSourceRef rls = CFSocketCreateRunLoopSource(kCFAllocatorDefault, cfSocket, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopCommonModes);
    CFRelease(rls);
}
@end

Somewhere else in the code, MyListener is instantiated and its method ListenOnPort is called, like so:

myListener = [[MyListener alloc] init];
[myListener ListenOnPort:IN_PORT withCallback:&ReadCallback];

No failures occur, but Data is never received. Source of packets is another computer on the same lan, and like I mentioned, they are seen by wireshark (udp with correct ip and port number).

This is the first time I try to use this framework. Any help is appreciated.

+1  A: 

Try changing:

addr.sin_port = port;

To:

addr.sin_port = htons(port);

(The simulator runs on Intel so you need to convert to network order)

St3fan
That was it. Thanks!
apalopohapa