我正在使用iOS应用中的CFStreams连接到主机名,例如:
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
outputStream = (__bridge NSOutputStream *)writeStream;
inputStream = (__bridge NSInputStream *)readStream;
但是我想知道如何从流中获取host
的远程IP地址吗?
答案 0 :(得分:0)
您可以获取文件描述符(Apple称为“本机句柄”),并使用典型的POSIX网络命令来获取地址:
从流中获取文件描述符:
CFDataRef handleData = (CFDataRef)CFReadStreamCopyProperty((__bridge CFReadStreamRef) inputStream, kCFStreamPropertySocketNativeHandle);
long length = CFDataGetLength(handleData);
uint8_t * buffer = malloc(length);
CFDataGetBytes(handleData, CFRangeMake(0, length), buffer);
int sock_fd = (int)*buffer;
获取该文件描述符的远程地址:
struct sockaddr addr;
socklen_t addr_len = sizeof(addr);
getpeername(sock_fd, &addr, &addr_len);
NSString * remoteAddr;
if (addr.sa_family == AF_INET) {
char addressString[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &((struct sockaddr_in *)&addr)->sin_addr, addressString, INET_ADDRSTRLEN);
remoteAddr = [[NSString alloc] initWithUTF8String:addressString];
} else if (addr.sa_family == AF_INET6) {
char addressString[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr, addressString, INET6_ADDRSTRLEN);
remoteAddr = [[NSString alloc] initWithUTF8String:addressString];
}
free(buffer);
// Now you have remoteAddr which will be a
// string representation of a IPv4 or IPv6 address!
NSLog(@"Remote Address: %@", remoteAddr);