Re: Getting Local IP Address in MacOS X
Re: Getting Local IP Address in MacOS X
- Subject: Re: Getting Local IP Address in MacOS X
- From: Rich Siegel <email@hidden>
- Date: Mon, 19 Sep 2005 19:55:36 -0400
On 9/17/05 at 12:19 PM, Ryan McGann <email@hidden> wrote:
> This question is asked quite frequently on this list. In summary here
> are the replies:
Ahoy Mates[1],
There's been a lot of good advice about regarding the various techniques
for discovering all of the network interfaces and their (possibly
multihomed) IP addresses.
One subject I haven't seen addressed, however, is how to discover the IP
address of the local end of an open communications channel. This is
useful in the case when you need to identify yourself to the remote
server at the protocol level (for example, when beginning an FTP
transfer[2] or SMTP handshake).
Here for your delectation is the code. Any suggestions for improvement
will be gratefully considered.
== 8< 8< 8< 8< 8< 8< ==
#include <arpa/inet.h>
[3] StCFAutoRelease<CFDataRef> socketHandle;
socketHandle.Assign((CFDataRef)CFReadStreamCopyProperty(fReadStream, kCFStreamPropertySocketNativeHandle));
[4] FailNIL(socketHandle, coreFoundationUnknownErr);
int socket = *reinterpret_cast<const int*>(CFDataGetBytePtr(socketHandle));
char addrBuffer[SOCK_MAXADDRLEN];
memset(addrBuffer, 0, sizeof(addrBuffer));
socklen_t addrLen = sizeof(addrBuffer);
sockaddr *addr = reinterpret_cast<sockaddr*>(addrBuffer);
sockaddr_in *in_addr = reinterpret_cast<sockaddr_in*>(addrBuffer);
[5] FailTest(0 == getsockname(socket, addr, &addrLen), kPOSIXErrorBase + errno);
FailTest(AF_INET == addr->sa_family, coreFoundationUnknownErr);
FailNIL(inet_ntop(addr->sa_family, &in_addr->sin_addr, buffer, bufferSize), kPOSIXErrorBase + errno);
== >8 >8 >8 >8 >8 >8 ==
[1] <http://www.talklikeapirate.com/piratehome.html>
[2] Yes, I know, CFNetwork offers an FTP implementation. :-)
[3] The "StCFAutoRelease" template class is a wrapper which maintains
retain/release for any CFTypeRef in an exception-safe way. The
Assign() method used here will capture the CFTypeRef without adding
a reference to it, so that it is properly released when the
StAutoRelease instance goes out of scope.
[4] The semantics of the various FailXXX() calls should be obvious
from context.
[5] kPOSIXErrorBase is a constant which is added to 'errno' to map
into a range of application-specific error messages.
Hope this is useful,
R. (on this day, pronounced "Arrrrrr.")
--
Rich Siegel Bare Bones Software, Inc.
<email@hidden> <http://www.barebones.com/>
Someday I'll look back on all this and laugh... until they sedate me.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Macnetworkprog mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden