How to create an IP address and port in NSData to work with

I am working with a library called GCDAsyncUDPSocket

and there is a method that required me to pass the IP address and port as NSData


Thanks for the help.


source to share

1 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 what you need is 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, "", &ip.sin_addr);

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


Here is some documentation at sockaddr




All Articles