Re: Find local IP address from an NSStream
Re: Find local IP address from an NSStream
- Subject: Re: Find local IP address from an NSStream
- From: Dustin Voss <email@hidden>
- Date: Wed, 21 Jun 2006 00:07:04 -0700
On 20 Jun 2006, at 6:51 AM, Craig Dooley wrote:
I have created a socket pair by calling [NSStream
getStreamsToHost:port:inputStream:outputStream:]. Is there a way to
get the underlying socket from the outputSocket, or find out the local
IP of the connection?
NSInputStream is toll-free bridged with CFReadStream. Get the
kCFStreamPropertySocketNativeHandle property from the CFReadStream,
then use CFSocketCreateWithNative to get a CFSocket. Then you can
call CFSocketCopyAddress.
Of course, that returns binary data; if you want the address in
string form, you have to determine whether it is an IPv4 or IPv6
address. Here's the code my AsyncSocket class uses for that, where
cfaddr is the returned CFData object.
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
struct sockaddr *pSockAddr = (struct sockaddr *) CFDataGetBytePtr
(cfaddr);
struct sockaddr_in *pSockAddrV4 = (struct sockaddr_in *) pSockAddr;
struct sockaddr_in6 *pSockAddrV6 = (struct sockaddr_in6 *)pSockAddr;
const void *pAddr = (pSockAddr->sa_family == AF_INET) ?
(void *)(&(pSockAddrV4->sin_addr)) :
(void *)(&(pSockAddrV6->sin6_addr));
const char *pStr = inet_ntop (pSockAddr->sa_family, pAddr, addrBuf,
sizeof(addrBuf));
if (pStr == NULL) [NSException raise: NSInternalInconsistencyException
format: @"Cannot convert address to string."];
return [NSString stringWithCString:pStr encoding:NSASCIIStringEncoding];
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden