Michael C. Toren on 3 Mar 2004 15:45:03 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] determining my IP address in C


On Wed, Mar 03, 2004 at 08:14:42AM -0500, Jeff Abrahamson wrote:
> I want to determine my own IP address.
> 
> A kludgy way is to bind to a high port, send myself (on 127.0.0.1) a
> packet containing only a long random number, and look at the from
> address.  Even then I might see 127.0.0.1, though.
> 
> I bet there's a better way.  Anyone know?

A similar question was raised on the list a little more than a year ago,
but unfortunately with a misleading "Subject:" of "proc filesystem"; see
<http://lists.netisland.net/archives/plug/plug-2002-12/threads.html#00478>
for more information.

In short, virtually every networked machine has at least two interfaces
(the loopback, and an egress interface), and therefore virtually every
networked machine has more than one IP address.  What you're really asking
is, "How can I determine what my source address will be when communicating
with a particular destination host?"

The most common, and most portable technique I know of is to create a
UDP socket(2), fill in the destination address, call connect(2) to cause
the kernel to fill in the source address with the one it intends to use
to send UDP packets to the specified destination address, and finally to
query the source address by calling getsockname(2).  Additionally, as this
technique never writes to the UDP socket, it results in no network traffic
being generated.  For an example implementation in perl, please see
<http://michael.toren.net/code/findsource.pl>.

> If the box has multiple interfaces, the above fails.  Is their a way
> to get all the addresses that are me?

That's a different question altogether, and one that's much harder to
answer in a portable manner.  A similar question was raised on the list
more than two years ago; for more information, see
<http://lists.netisland.net/archives/plug/plug-2001-12/threads.html#00497>.
However, based on the first question you asked, most likely this isn't the
path you'll want to take.

-mct
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug