从以下文档GCDAsyncUdpSocket
:
该localAddress
方法返回包装在 NSData 对象中的 sockaddr 结构。
以下代码将数据解包为sockaddr 结构,并将 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