gpt4 book ai didi

ios - 如何从 iOS 中的 CFStream 获取远程地址?

转载 作者:行者123 更新时间:2023-11-29 05:53:28 24 4
gpt4 key购买 nike

我正在我的 iOS 应用程序中使用 CFStreams 连接到主机名,例如:

CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);

outputStream = (__bridge NSOutputStream *)writeStream;
inputStream = (__bridge NSInputStream *)readStream;

但我想知道如何从流中获取主机的远程IP地址?

最佳答案

您可以获得文件描述符(Apple 称之为“ native 句柄”),并使用典型的 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_storage addr;
socklen_t addr_len = sizeof(addr);
getpeername(socket, (struct sockaddr *)&addr, &addr_len);
NSString * remoteAddr;
if (addr.ss_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.ss_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);

关于ios - 如何从 iOS 中的 CFStream 获取远程地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com