我是iOS / MacOS编程的新手,并没有找到我理解的任何示例。我想这只是几行代码,所以很抱歉,如果这已经涵盖了,但对于我的生活,我找不到它。
我正在使用CFStreamCreatePairWithSocketToHost来创建输入/输出流。我只想获取本地端点信息(特别是IP地址,真的不关心端口)。我已经从我的服务器获取公共IP信息,但出于安全/日志记录的原因,我也需要本地地址。
这是在iOS上,而不是MacOS,如果重要的话。
答案 0 :(得分:7)
以下代码演示了如何获取本地套接字地址。它适用于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);