2012-01-23

Getting LAN IP address of local computer

Using Python to get the LAN IP address of the local computer:

If we use:

import socket
socket.gethostbyname('localhost')

we will get '127.0.0.1' which may not be what we want due to the presence of the hosts file.

We could use:

import socket
socket.gethostbyname(os.environ['COMPUTERNAME'])

we will get something like '192.168.0.xxx' which is more likely what we want.

The above code fragment works in Windows XP, may need adjustment in getting the host name in other OS.


No comments: