以下代碼演示瞭如何獲取本地套接字地址。它適用於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);
非常感謝,正是我所需要的!現在我也知道如何獲得本地套接字句柄來處理任何我可能需要的東西。直到一些數據包回來後,我才需要這些信息,但是直到I/O完成才知道套接字是無效的。 – eselk