Find hostname of a computer - Python

There are multiple methods to retrieve the hostname of a computer using Python. The "socket" module grants access to the BSD socket interface and is accessible on various platforms like modern Unix systems, Windows, Mac OS X, BeOS, and OS/2. To acquire the hostname, employ the socket module's gethostname() function, which returns a string containing the hostname of the machine currently executing the Python interpreter.

import socket print(socket.gethostname())


import socket print(socket.gethostbyaddr(socket.gethostname())[0])

How to get fully qualified host name?

The gethostname() function may not always provide the fully qualified domain name. For a complete domain name, you can use the socket.getfqdn([name]) function, which returns the fully qualified domain name for the specified "name." If no name is provided or it is empty, the function interprets it as referring to the local host.

import socket print (socket.getfqdn(""))

The Python platform module encompasses functionalities to access information about the hardware, operating system, and interpreter version on the platform where the program is executed. The platform.node() function specifically retrieves the network name of the computer.

import platform print(platform.node())

Solutions relying on the HOST or HOSTNAME environment variables lack portability. While they might function on your system during manual execution, they might fail in specific environments like cron jobs.

How to get username of a computer

The Python os module offers a platform-independent approach to utilizing operating system-specific features. However, the os.uname() function returns a 5-tuple that identifies the current operating system, but this feature is exclusively available on Unix-like systems.

import os myhost = os.uname()[1] print(myhost)


To obtain the hostname of a computer using Python, you can use the "socket" module's gethostname() function, which returns the local host's name. However, for a fully qualified domain name, the socket.getfqdn([name]) function should be utilized.