Retrieving the network configuration of a local machine
Before doing anything else, let's ask in the Python language, What's my name?. In networking terms, this is equivalent to finding out the machine's name or the host's name. On the shell command-line, this can be discovered by using the hostname
command. In Python, you can do this by using the socket module.
>>> import socket >>> socket.gethostname() 'debian6box.localdomain.loc'
Now, we would like to see the local machine IP. This can be seen by using the ifconfig
command in Linux and by using the ipconfig
command in the Windows OS. But, we'd like to do this in Python by using the following built-in function:
>>> socket.gethostbyname('debian6box.localdomain.loc') '10.0.2.15'
As you can see, this is the IP of the first network interface. It can also show us the IP of the loopback interface (127.0.0.1) if your DNS or hostfile has not been configured properly...