How to Find IP address of a website in Python
How To Python

How to Find IP address of a website in Python

Mishel Shaji
Mishel Shaji

An IP (Internet Protocol) address is used to uniquely identify a device connected in a network. There are two types of IP address. IPv4 and IPv6.

This post explains how to find the IP of a website using Python. We'll be using gethostbyname() method in socket library for this.

First import socket library to the code.

import socket as s

Now we can use the gethostbyname() method to find IP address of the website. Let's test with geekinsta.com.

import socket as s
host = 'geekinsta.com'
print(f'IP of {host} is {s.gethostbyname(host)}')

This code will print the following in the console.

IP of geekinsta.com is 149.248.20.148

It works fine. But this code will create error if it could not find the IP of the given website. For example, if you enter an invalid domain name,this error will be displayed.

Traceback (most recent call last):
  File "c:/Users/ASUS/Desktop/test.py", line 3, in <module>
    print(f'IP of {host} is {s.gethostbyname(host)}')
socket.gaierror: [Errno 11001] getaddrinfo failed

To handle this, we're placing our code in try-except block.

import socket as s
try:
    host = 'geekinsta.comjhgfhj'
    print(f'IP of {host} is {s.gethostbyname(host)}')
except Exception as e:
    print('Failed to resolve IP: ', e)

The code works fine now. Happy coding. 👍