eemceebee eemceebee - 11 days ago 5
Objective-C Question

How to create ip address and port into NSData to work with

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.

Answer

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