4

I am working with a library called GCDAsyncUDPSocket and there is method that required me to pass the IP address and port as NSData.

Thanks for the help.

eemceebee
  • 2,656
  • 9
  • 39
  • 49

1 Answers1

5

From the header file:

 * Binds the UDP socket to the given address, specified as a sockaddr structure wrapped in a NSData object.
 * 
 * If you have an existing struct sockaddr you can convert it to a NSData object like so:
 * struct sockaddr sa  -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
 * struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];

So, you need a sockaddr:

#include <netinet/in.h>
#include <arpa/inet.h>

struct sockaddr_in ip;
ip.sin_family = AF_INET;
ip.sin_port = htons(6003);
inet_pton(AF_INET, "0.0.0.0", &ip.sin_addr);

NSData * discoveryHost = [NSData dataWithBytes:&ip length:ip.sin_len];

Here's some documentation on sockaddr - http://www.beej.us/guide/bgnet/output/html/multipage/sockaddr_inman.html

tomcheney
  • 1,750
  • 1
  • 17
  • 33
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
  • 4
    With iOS 7.1 SDK in Xcode 5.1.1 this code seems to need some tweaking. `inet_pton()` appears to be declared in `` which you will need in addition to `` (for the `sockaddr` struct), and the `sa_len` member being used in the call to `-[NSData dataWithBytes:length]` should be `sin_len` (not sure if that was originally a typo or a change in the SDK). – Jasarien Aug 18 '14 at 14:19
  • You can't use `ip.sin_len` without having set it yourself. It's not magically initialized. You have to initialize it. You can set it to `sizeof(ip)`. – Ken Thomases Nov 25 '16 at 04:01