Search code examples
objective-ciosasyncsocket

Null result on Converting NSData to NSString


I am facing a problem when converting NSData to NSString. I'm using UTF8Enconding but the result is null!!

Here is the data I receive <100226ab c0a8010b 00000000 00000000> it must be either 192.168.1.11 or 192.168.1.17.

This is the method I use to convert :

 NSString *ipAddress = [[NSString alloc] initWithData:address encoding:NSUTF8StringEncoding];

Is there anything wrong?!

By the way, This the did receive data delegate of GCDAsyncUdpSocket library.


Solution

  • From the documentation of GCDAsyncUdpSocket:

    The localAddress method returns a sockaddr structure wrapped in a NSData object.

    The following code unwraps the data to a sockaddr structure and converts the IP address to a NSString. It works with IPv4 and IPv6 addresses.

    #include <sys/socket.h>
    #include <netdb.h>
    
    NSData *data = ...; // your data
    NSLog(@"data = %@", data);
    
    // Copy data to a "sockaddr_storage" structure.
    struct sockaddr_storage sa;
    socklen_t salen = sizeof(sa);
    [data getBytes:&sa length:salen];
    
    // Get host from socket address as C string:
    char host[NI_MAXHOST];
    getnameinfo((struct sockaddr *)&sa, salen, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
    
    // Convert C string to NSString:
    NSString *ipAddress = [[NSString alloc] initWithBytes:host length:strlen(host) encoding:NSUTF8StringEncoding];
    NSLog(@"strAddr = %@", ipAddress);
    

    Output:

    data = <100226ab c0a8010b 00000000 00000000>
    strAddr = 192.168.1.11