Determine ip address

Mike Meyer mwm at mired.org
Thu May 5 05:35:23 EDT 2005


[Format recovered from top-posting.]

ontiscal at tenup.com writes:
> codecraig ha scritto:
>>    how can i use python to figure the ip address of the machine which
>> the python script is running on?  I dont mean like 127.0.0.1....but i
>> want the external IP address (such as ipconfig on windows displays).
>
> http://checkip.tk/

That won't work if you're on a NAT'ed network - it will instead return
the external address of the NAT gateway. ipconfig displays the ip
address(es) of the interfaces on the current machine.

You need to use the socket.socket.getsockname method:

py> import socket
py> s = socket.socket()
py> s.connect(("google.com", 80))
py> s.getsockname()
('192.168.1.1', 57581)
py> 

The local ethernet card is 192.168.1.1, the local port for the socket
is 57581.

Note that the presence of multiple interface cards makes the question
ambiguous.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list