從GCDAsyncUdpSocket
文檔:
的localAddress
方法返回包裝在 NSData對象sockaddr結構體。
以下代碼將數據解開爲sockaddr structure並將IP地址轉換爲NSString
。它適用於IPv4和IPv6地址。
#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);
輸出:
data = <100226ab c0a8010b 00000000 00000000>
strAddr = 192.168.1.11
你檢查nslogging'address'是含有什麼呢? –
是的,就像我說的,它的<100226ab c0a8010b 00000000 00000000> – Danialzo
參考這個http://stackoverflow.com/questions/2467844/convert-utf-8-encoded-nsdata-to-nsstring – zahreelay