The hostname is used to set a human-readable name for a system. The hostname is the name of the host which is connected to a network or internet. By using the hostname the host can be easily identified in a human-readable format without using an IP address etc. Python provides different methods to find hostname or fully qualified domain name (FQDN) which are very similar. The gethostname() is the most popular method to display the current system hostname.
Display Hostname with gethostname() Method
The gethostname() method is provided via the socket module. So first the socket module should be imported to run gethostname() method. The hostname is returned as string.
import socket print(socket.gethostname())
Display Fully Qualified Domain Name (FQDN)
The gethostname() method returns only the hostname without the complete qualified domain name. The fully quliafied domain name or FQDN is internet compatible unique name of the host. The getfqdn() method requires an IP address which can be IPv4 or IPv6. The getfqdn() returns the FQDN as string.
import socket fqdn = socket.getfqdn("184.108.40.206") print(fqdn)
Find Hostname with platform() Method
Python provides the platform module which provides methods related to the current platform. The platform.node() method is used to print the current hostname.
import platform hostname = platform.node() print(hostname)
Find Hostname with uname() Method
Another way to return the hostname of the current system the os.uname() method. The os module provides operating system-related methods and features. The uname is a popular command provided by Linux systems to print operating systems and host-related information. The uname() method name comes from the uname command. The uname() method returns multiple information as a list. The second item of the list is the hostname of the system.
import os hostname = os.uname() print(hostname)