gpt4 book ai didi

ios - CFStreamCreatePairWithSocketToHost 获取本地端点地址

转载 作者:可可西里 更新时间:2023-11-01 02:35:23 25 4
gpt4 key购买 nike

我是 iOS/MacOS 编程的新手,还没有找到任何我能理解的例子。我想只需几行代码就可以做到这一点,很抱歉,如果这已经涵盖了,但我无法找到它。

我正在使用 CFStreamCreatePairWithSocketToHost 创建输入/输出流。我只想获取本地端点信息(特别是 IP 地址,真的不关心端口)。我已经从我的服务器获取了公共(public) IP 信息,但出于安全/日志记录的原因,我还需要本地地址。

如果重要的话,这是在 iOS 上,而不是 MacOS 上。

最佳答案

以下代码演示了如何获取本地套接字地址。它适用于 IPv4 和 IPv6 地址。 (它不止几行,也许有人知道更短的解决方案。)

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

// Create socket pair:
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStringRef remoteHost = CFSTR("localhost");
CFStreamCreatePairWithSocketToHost(NULL, remoteHost, 5555, &readStream, &writeStream);

// Write something (the socket is not valid before you read or write):
CFWriteStreamOpen(writeStream);
CFWriteStreamWrite(writeStream, "Hello\n", 6);

// Get the native socket handle:
CFDataRef socketData = CFWriteStreamCopyProperty(writeStream, kCFStreamPropertySocketNativeHandle);
CFSocketNativeHandle socket;
CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&socket);

// Get the local socket address from the socket handle:
struct sockaddr_storage sa;
socklen_t salen = sizeof(sa);
getsockname(socket, (struct sockaddr *)&sa, &salen);

// Get numeric host and port from socket address:
char host[NI_MAXHOST];
char service[NI_MAXSERV];
getnameinfo((struct sockaddr *)&sa, salen, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST|NI_NUMERICSERV);

NSLog(@"local address: %s, local port: %s", host, service);

关于ios - CFStreamCreatePairWithSocketToHost 获取本地端点地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12750935/

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