title: Sending UDP packets in Objective C: packet arriving without any data
body: <p>I'm trying to send UDP packets in objective C. More specifically, building with xcode targeting the iphone 6.1 simulator.</p>
  
  <p>I can't seem to actually receive the data I send. Weirdly, I do get a data event... the data's just been truncated to length 0.</p>
  
  <p>I've cut it down as much as I can, to make a dead simple test I think should pass.</p>
  
  <pre><code>#import "UdpSocketTest.h"
  #include &lt;arpa/inet.h&gt;
  #import &lt;CoreFoundation/CFSocket.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  
  @implementation UdpSocketTest
  
  static int receivedByteCount = 0;
  void onReceive(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info);
  void onReceive(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
      // this gets called once, but CFDataGetLength(data) == 0
      receivedByteCount += CFDataGetLength(data);
  }
  
  -(void) testUdpSocket {
      struct sockaddr_in addr;
      memset(&amp;addr, 0, sizeof(addr));
      addr.sin_len = sizeof(addr);
      addr.sin_family = AF_INET;
      addr.sin_port = htons(5000); // &lt;-- doesn't really matter, not sending from receiver
      inet_pton(AF_INET, "127.0.0.1", &amp;addr.sin_addr);
      CFSocketContext socketContext = { 0, (__bridge void*)self, CFRetain, CFRelease, NULL };
  
      // prepare receiver
      CFSocketRef receiver = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_DGRAM, IPPROTO_UDP ,kCFSocketDataCallBack, (CFSocketCallBack)onReceive, &amp;socketContext);
      CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(NULL, receiver, 0), kCFRunLoopCommonModes);
      CFSocketConnectToAddress(receiver, CFDataCreate(NULL, (unsigned char *)&amp;addr, sizeof(addr)), -1);
  
      // point sender at receiver
      CFSocketRef sender = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_DGRAM, IPPROTO_UDP, kCFSocketDataCallBack, (CFSocketCallBack)onReceive, &amp;socketContext);
      CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(NULL, sender, 0), kCFRunLoopCommonModes);
      CFSocketConnectToAddress(sender, CFSocketCopyAddress(receiver), -1);
  
      // send data of sixty zeroes, allow processing to occur
      CFSocketSendData(sender, NULL, (__bridge CFDataRef)[NSMutableData dataWithLength:60], 2.0);
      [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
  
      // did the data arrive?
      STAssertTrue(receivedByteCount &gt; 0, @"");
      // nope
  }
  @end
  </code></pre>
  
  <p>What am I doing wrong? I know it's something obvious, but I can't see it.</p>