determine IP
exarkun at divmod.com
exarkun at divmod.com
Sun Nov 7 11:53:57 EST 2004
On Sun, 7 Nov 2004 11:38:57 -0500, Ed Leafe <ed at leafe.com> wrote:
>On Nov 7, 2004, at 11:04 AM, exarkun at divmod.com wrote:
>
> >> is there a cross platform way to determine a local machines IP on a
> >> network (LAN or internet) in python?
> >>
> >
> > s = socket.socket()
> > s.connect(('google.com', 80))
> > print s.getsockname()
>
> If you are on a NAT machine on the local network, the above will
> return the public IP of the network. If you change the target from
> 'google.com' to a machine on your subnet that will accept the
> connection, you'll get the local IP address.
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)
>>>
Jp
More information about the Python-list
mailing list