18

Does anyone have any good tutorials on sending UDP packets from the iPhone SDK?

EDIT:

Was actually really easy to do this...

RTFM!

After including AsyncUdpSocket just add this in header:

AsyncUdpSocket *socket;

And in main:

NSData *data = ... 
[socket sendData:data toHost:@"192.168.x.x" port:5002 withTimeout:-1 tag:1];

When testing don't forget to allow UDP communication on your server firewall!

ingh.am
  • 25,981
  • 43
  • 130
  • 177
  • A bit of history ... at one stage there was the absolutely INCREDIBLE AsyncSocket library, originally created by the mysterious Dustin J. Voss. (sometimes known as CocoaAsyncSocket.) At one point it came with easy UDP example code and it was central to iOS development. Probably still valuable if you can dig it up. It was an incredible library. – Fattie May 22 '16 at 13:14
  • how to handle if the IP address varies – remyr3my Jul 10 '17 at 08:05
  • @Cyph3r You would need to use some custom logic to set a `NSString` variable, which you can pass in the `toHost` param. Or, alternatively use a domain and setup a DNS record instead of using the IP address and update that where necessary. It completely depends on what you're trying to do. – ingh.am Jul 27 '17 at 09:13

2 Answers2

17

CocoaAsyncSocket is a nice library that contains a class called AsyncUdpSocket which is an Obj-C wrapper around the lower-level socket API.

Daniel Dickison
  • 21,832
  • 13
  • 69
  • 89
  • I'll give you correct answer as you got me on the way! For anyone reading this question with same issue I posted some code as a edit in the question. – ingh.am Nov 10 '10 at 00:52
  • Link updated to what appears to be its new home on github: https://github.com/robbiehanson/CocoaAsyncSocket – Daniel Dickison Mar 11 '13 at 17:11
2

You can use the CFNetwork framwork to create a UDP socket with CFSocket. Here is the CFSocket reference.

Donald
  • 1,718
  • 10
  • 18
  • So to send a UDP packet to my server do I just use CFSocketSendData? – ingh.am Nov 09 '10 at 22:00
  • Yes, after you CFSocketCreate with IPPROTO_UDP, you can use CFSocketSendData. The Mac Network Programming mailing list is a good place to find examples: http://lists.apple.com/archives/macnetworkprog/ – Donald Nov 09 '10 at 22:26
  • AsyncUdpSocket was much more simple! :) – ingh.am Nov 10 '10 at 00:54