In this blog, we will find IP address of a website using Python socket module.
Python has good support for creating network programs
Use gethostbynme() function to find IP Address of a website
This function is available in socket module
We need to provide the name of the website to gethostbyname() function and it will returns its IP Address
Code : Creating a program that will find IP Address of a website
First of all import socket module.
Ask user to input complete url or website
host = input('Enter a website to find its IP Address: ')
Then using gethostbyname() function to print IP Address of a website
Enter a website to find its IP Address: www.facebook.com 184.108.40.206
Now, this above code will run without any error if user types correct website or url. But in case user does typing mistake or enter a website that does not exists, program will return an error called ‘gaierror (Get Address Information Error). Below is the error for invalid website
Enter a website to find its IP Address: www.fasddadsa.com Traceback (most recent call last): File "C:/Users/rohit/PycharmProjects/pythonProject/main.py", line 3, in <module> print(socket.gethostbyname(host)) socket.gaierror: [Errno 11001] getaddrinfo failed
To handle gaierror error, we can make use of try and except. Below is the complete program.
import socket host = input('Enter a website: ') try: print(socket.gethostbyname(host)) except socket.gaierror: print('Invalid website')
Enter a website: www.facebook.com 220.127.116.11
Output(Invalid website entered)
Enter a website: www.sfdsssd.com Invalid website