Finding IP address of website

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.

import socket

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

print(socket.gethostbyname(host))

Output

Enter a website to find its IP Address: www.facebook.com
157.240.16.35

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')

Output(Successful)

Enter a website: www.facebook.com
157.240.16.35

Output(Invalid website entered)

Enter a website: www.sfdsssd.com
Invalid website
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s