Python socket module can be used to get the IP address from a hostname.
The socket module is part of the Python core libraries, so we don’t need to install it separately.
Python socket module gethostbyname()
function accepts hostname argument and returns the IP address in the string format.
Here is a simple example in the Python interpreter to find out the IP address of some of the websites.
Note: If the website is behind a load-balancer or working in the cloud, you might get a different result for the IP address lookup.
For example, try to run the above command for google.com or facebook.com. If you are not in the same location as mine (India), chances are that you will get a different IP address as output.
Let’s look at an example where we ask user to enter a website address and then print its IP address.
Here is another example to pass the hostname as a command-line argument to the script. The script will find the IP address and print it.
Output:
If the hostname doesn’t resolve to a valid IP address, socket.gaierror
is raised. We can catch this error in our program using try-except block.
Here is the updated script with exception handling for invalid hostname.
Output:
Reference: Socket Module API Docs
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.