python get hostname code example

Example 1: python get ip from hostname

## importing socket module
import socket
## getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
## getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
## printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")

Example 2: how to print hostname in python

# Use socket and its gethostname() functionality. 
# This will get the hostname of the computer where the Python interpreter is running:
import socket
print(socket.gethostname())