The Python socket module gethostbyname() function allows us get the IPv4 address from a given name (computer, server, domain, etc.).
import socket
host_name = socket.gethostname()
IP_address_of_Computer = socket.gethostbyname(host_name)
IP_address_of_Google = socket.gethostbyname("google.com")
print(IP_address_of_computer)
print(IP_address_of_Google)
#Output:
10.0.0.220
172.217.4.46
When working with connections between different servers in Python, the ability to get the IP address of a client, computer or website can be very useful.
The Python socket module provides us a low-level networking interface.
One useful function from the socket module is the gethostbyname() function. gethostbyname() returns the IPv4 address given a host name.
With gethostbyname(), we can get your IP address or the IP address of any website.
Using gethostbyname() to Get the IP Address of a Computer Using Python
With the gethostbyname() function, you 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
Using gethostbyname() 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 gethostbyname() in Python.