次のコードは、ローカル ソケット アドレスを取得する方法を示しています。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);