determine IP

Michael Fuhr mfuhr at fuhr.org
Sun Nov 7 18:47:23 CET 2004


Ed Leafe <ed at leafe.com> writes:

> On Nov 7, 2004, at 11:53 AM, exarkun at divmod.com wrote:
>
> >   The above code will _always_ return the local IP address, regardless 
> > of NAT configuration.  For example, running on my desktop:
> >
> >>>> import socket
> >>>> s = socket.socket()
> >>>> s.connect(('google.com', 80))
> >>>> print s.getsockname()
> >     ('192.168.42.4', 40044)
>
> 	Not OMM:
>
>  >>> import socket
>  >>> s = socket.socket()
>  >>> s.connect(('google.com', 80))
>  >>> s.getsockname()
> ('66.66.222.137', 55096)
>  >>>
> 	The local IP address is in the 192.168 subnet.

Is your machine dual-homed?  getsockname() returns the IP address
if the interface used for the connection, so if you have multiple
interfaces (e.g., one outside and one inside) then you'll get the
one being used.  Run that script on a machine whose only interface
is on the inside network (i.e., a machine that must route through
the box doing the NAT) and you'll see a private address.

-- 
Michael Fuhr
http://www.fuhr.org/~mfuhr/



More information about the Python-list mailing list