Find hostname of a computer - Python
There are several ways to find the hostname of a computer in Python. The "socket" module in Python provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, Mac OS X, BeOS, OS/2, and probably additional platforms. In order to get the hostname of a computer, you can use socket and its gethostname() functionality. The gethostname() return a string containing the hostname of the machine where the Python interpreter is currently executing.
import socket
print(socket.gethostname())
or
import socket
print(socket.gethostbyaddr(socket.gethostname())[0])
How to get fully qualified host name?
The gethostname() doesn't always return the fully qualified domain name. The socket.getfqdn([name]) return a fully qualified domain name for name. If name is omitted or empty, it is interpreted as the local host.
import socket
print (socket.getfqdn("209.191.88.254"))
output
d.mx.mail.yahoo.com
The platform module in Python includes tools to see the platform's hardware, operating system , and interpreter version information where the program is running. The platform.node() returns the computer's network name.
import platform
print(platform.node())
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.
How to get username of a computer
The os module in Python provides a portable way of using operating system dependent functionality. The os.uname() return a 5-tuple containing information identifying the current operating system, but it is available only on unix-like systems.
import os
myhost = os.uname()[1]
print(myhost)
Related Topics
- How To Find IP Address In Python
- Send mail from Gmail account using Python
- Retrieving Email from a POP3 Server - Python
- Retrieving Web Pages with HTTP using Python
- How to open a web browser using Python
- Creating an FTP client in Python
- Socket Programming in Python
- Multi threaded socket programming in Python