Skip to content

How to get hostname in Python?

There are a few different ways to get the hostname of a system in Python. The socket module in Python gives access to the BSD socket interface. It is accessible on the latest Unix frameworks, Windows, Mac OS X, BeOS, OS/2, and most likely extra stages. So as to get the hostname of a PC, you can utilize socket and its gethostname() function. The gethostname() return a string containing the hostname of the machine where the Python translator is right now executing.

import socket
print(socket.gethostname())

You can also use the platform module. The platform module in Python incorporates tools to see the platform equipment, OS and interpreter version data where the program is running. The platform.node() returns the PC’s system name.

import platform
platform.node()

Or OS Module.

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

Or this, when you are writing a cron job.

import socket
socket.gethostbyaddr(socket.gethostname())[0]
See also  Creating Interactive Corona Virus(COVID-19) Tracking Dashboard using Python

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.