import socket
try:
my_host = socket.gethostname()
my_ip = socket.gethostbyname(my_host)
print("Hostname : ",my_host)
print("IP : ",my_ip)
except:
print("Unable to get Hostname and IP address")
The output will change based on your hosting server.
import socket
print("Fully Qualified Domain Name:", socket.getfqdn())
Retrieve all IP addresses for a host using gethostbyname_ex().
import socket
print(socket.gethostbyname_ex(socket.gethostname()))
When setting up or monitoring a web server, retrieving the hostname and IP address can be essential for debugging or configuring network settings. This can help in identifying server locations, resolving domain names, or diagnosing network issues during deployment.
Handle common errors like socket.gaierror
when network-related issues occur. For example, if the host can't be resolved, using a try-except block can prevent crashes:
import socket
try:
print(socket.gethostbyname('invalid.host'))
except socket.gaierror as e:
print(f"Error: {e}")