Getting local IP address...

Aaron Rhodes arhodes at psionic.com
Wed Jul 19 18:23:15 EDT 2000


Mike Fletcher wrote:
> 
> The primary problem with #1 is complex network configurations. For instance,
> here is what the code gives you on my machine (and my configuration is not
> that complex in the grand scheme of things)...
> 
> >>> import socket
> >>> socket.gethostbyname( socket.gethostname())
> '192.0.2.201'
> 
> Which seems perfectly reasonable, except that that is actually an address on
> our VPN, and is completely un-addressable by the outside world.
> (Incidentally, you likely get the same information from the Linux hackery,
> since it only accesses "the first" ethernet adapter, is, effectively, doing
> exactly the same thing as gethostbyname, just in an obscure way, and you
> still are left not knowing what is connected to the Internet).

Just to clarify -- the Linux hack does things a tad different
than the socket.gethostbyname( socket.gethostname() ) call...
The socket.gethostbyname method relies on an entry in /etc/hosts
or a valid DNS entry (or whatever nsswitch.conf says to use
actually) under hosts: .  If these two things are broken or don't
exist the call will fail as in:

>>> import socket
>>> print socket.gethostbyname_ex(socket.gethostname())
Traceback (innermost last):
  File "<stdin>", line 1, in ?
socket.error: host not found

*Note: I only tried this on Linux since that's what I'm on right now.

However, the Linux fcntl method will work without valid DNS/hosts file.

The other issue here is that if multiple IP addresses are used,
there's really not a good way to tell which one was used to send
a packet to particular destination unless you use the reflection
method as previously described (or sniff the wire in non-promiscuous
mode to see what your machine is sending -- fairly tedious).  If you 
need to know which address "will be used" to send a packet somewhere
before 
it is sent -- i.e. to locate the "external" interface
before it's used, then you could perhaps look at the default route on
the system and compare to the machine you are trying to connect to...
or have the user tell you.

This is an interesting problem...who would have thought.

Aaron
arhodes at psionic.com



More information about the Python-list mailing list