How can I use Python to get the system hostname?


Question

I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.

1
603
9/13/2016 4:00:53 PM

Accepted Answer

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())
931
2/10/2015 11:02:05 PM

Both of these are pretty portable:

import platform
platform.node()

import socket
socket.gethostname()

Any solutions using the HOST or HOSTNAME environment variables are not portable. Even if it works on your system when you run it, it may not work when run in special environments such as cron.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon