To get the public IP address of your computer, you can use the Python socket module gethostbyname() function.

import socket

host_name = socket.gethostname()
IP_address = socket.gethostbyname(host_name)

print(IP_address)

#Output:
10.0.0.220

You can also use gethostbyname() to get the IP address of a website.

import socket

IP_address = socket.gethostbyname("google.com")

print(IP_address)

#Output:
172.217.4.46

When working with connections between different servers in Python, the ability to get the IP address of a user, computer or website can be very useful.

The Python socket module provides us a low-level networking interface.

With the socket module comes the gethostbyname() function which returns the IPv4 address given a host name.

With gethostbyname(), we can get your IP address or the IP address of any website.

How to Get the IP Address of a Computer Using Python

With the gethostbyname() function, we can get the public IP address of your computer.

To get the public IP address of my computer, first, we use the gethostname() function and then pass the host name to gethostbyname().

Below is an example of how you can get the public IP address of your computer with Python.

import socket

host_name = socket.gethostname()
IP_address = socket.gethostbyname(host_name)

print(IP_address)

#Output:
10.0.0.220

How to Get the IP Address of a Website Using Python

You can also use gethostbyname() to get the public IP address of a website.

To get the IP address of a website, you just pass the domain name of the website to gethostbyname().

Below is an example showing how to get the IP address of a website with Python.

import socket

IP_address = socket.gethostbyname("google.com")

print(IP_address)

#Output:
172.217.4.46

Hopefully this article has been useful for you to learn how to use Python to get the IP address of a computer or website.

Categorized in:

Python,

Last Update: February 26, 2024