4 Ways To Get Hostname Using Python

Python has many applications in the networking field. Developers often use it as a medium to communicate with others on your network. Between these communications, it’s important to get the hostname in Python.

Python Get Hostname is a way to fetch the device name or alias within the network either by using its IP or domain. Hostnames generally refer to the names of the devices which can be used to further distinguish between them. Moreover, you can also get the name of the host where your Python interpreter is running.

What is a Hostname?

The hostname is an identifying name/alias which is maybe unique to every device connected over a network node. This hostname can be completely unique and can be used to differentiate between devices. Usually, the combinations of ascii characters are used as Hostname, but it may vary depending on the network.

In many cases, if the device hostnames are changed forcefully, two or more devices can have the same Hostname. Even tho they have the same hostname, but they can have different MAC addresses.

Ways to Get Hostname in Python

There are several ways to get a hostname in Python by using modules. Each of these modules has different ways of functioning and can behave differently on different operating systems. Some of them might work perfectly in Linux and not in Windows or vice versa. Make sure you check them on all platforms before implementing them in your code.

Following are some fo the ways you can get hostname –

  1. Socket gethostname Function
  2. Platform Module
  3. Os Module
  4. Using socket gethostbyaddr Function

1. Socket gethostname Function

Code:

import socket
print(socket.gethostname())

Output:

DESKTOP-PYTHONPOOL

Explanation:

Socket module is one of the most important networking modules in Python. You can communicate with sockets and connect to other devices using them. In the above example, we imported the socket module in the first line and then used the function gethostname() to get the Hostname of the device. This function will return the device hostname where the python code is interpreted.

2. Platform Module

Code:

import platform
print(platform.node())

Output:

DESKTOP-PYTHONPOOL

Explanation:

Similar to the socket module, the platform module is a widely used module to access platform information. This information includes host names, IP, Operating system, and much other information. We imported the platform in the first-line and then called the node() function to get the device’s hostname. Node function returns the computer hostname if available.

3. Os Module

Code:

import os, platform

if platform.system() == "Windows":
    print(platform.uname().node)
else:
    print(os.uname()[1])   # doesnt work on windows

Output:

DESKTOP-PYTHONPOOL

Explanation:

You might’ve seen os module used in handling files and directories in python, but it can also be used to get the device name. uname() is the function that returns the hostname of the system. Unfortunately, this cannot be used on Windows devices, and you have to use and if clause for it to work.

4. Using socket gethostbyaddr Function

Code:

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

Output:

DESKTOP-PYTHONPOOL

Explanation:

Using gethostbyaddr will take care of the hostnames which are linked to their IPs. Normally, on a local network, it’ll return the same hostname passed as a parameter, but on remote networks, it can return the remote hostnames (It’s mentioned in the next sections).

Get Hostname from URL in Python

Many times, you need to access the domain names from the URLs you have. This can be done in many ways in Python by using Regex, urllib, string splitting, or other modules. All of them work most of the time, but urllib is optimal to work all the time because it’s from the networking module and is present by default. So you don’t have to code anything fancy for it.

Code:

<pre class="wp-block-syntaxhighlighter-code">from urllib.parse import <a href="https://www.pythonpool.com/urlparse/" target="_blank" rel="noopener">urlparse</a>

url = urlparse('https://www.pythonpool.com/for-vs-while-loop-python/' )
host = '{uri.scheme}://{uri.netloc}/'.format(uri=url)
print(host)</pre>

Output:

https://www.pythonpool.com/

Explanation:

We first start by importing urlparse from the urllib parser. This can be used to parse the URLs into understandable strings. As soon as we initialize urlparse() with a URL, it’ll break down the URL into scheme, netloc, params, query, and fragment. Then we can use the scheme and netlock to get the protocol and hostnames from the URL.

Get Hostname from IP in Python

Sometimes, you have the IP addresses in your code results. Then by using them, you can easily deduce the hostnames of the servers. But importantly, your IP should be working and reachable by your network. In the following example, I’ve used 8.8.8.8 as IP, which is Google’s DNS.

Get Hostname from IP in Python

Code:

import socket
print(socket.gethostbyaddr("8.8.8.8"))

Output:

('dns.google', [], ['8.8.8.8'])

Explanation:

We start by importing the socket module and then calling the gethostbyaddr function. Then you can pass the IP as a string to it. It returns (hostname, alias list, IP Address List) as a tuple. Then you can access the hostname by using tuple indexing.

See Also

References

  1. socket.gethostname(): Return a string containing the hostname of the machine where the Python interpreter is currently executing.
  2. socket.gethostbyaddr(): Return a triple (hostname, aliaslist, ipaddrlist).
  3. platform.node(): Returns the computer’s network name (may not be fully qualified!). An empty string is returned if the value cannot be determined.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments