Displaying Hostname and IP address in Python

In this post, we’ll use the Python programming language to display the hostname and IP address. IP (Internet Protocol) is a fundamental networking concept that enables address assignment capability in a network, as we all know.

Python offers a wide range of networking applications. It’s a popular way for developers to communicate with others on your network. It’s critical to retrieve the hostname in Python between these communications.

Python gethostname() is a method for retrieving a network device’s name or alias by utilizing its IP or domain. Hostnames are the names of the devices that can be used to differentiate them. You can also obtain the host’s name on which your Python interpreter is installed.

What is the definition of a hostname?

The hostname is a name or alias that is possibly unique to each device connected to a network node. This hostname does not have to be unique and can be used to distinguish between devices. Hostnames are usually ASCII characters, but this might change depending on the network. When device hostnames are changed forcibly, it is common for two or more devices to have the same Hostname. Even though they share the same hostname, their MAC addresses can differ.

Different ways to get the hostname in Python

Using modules, there are numerous ways to retrieve a hostname in Python. Each of these components works uniquely and can behave differently depending on the operating system. Some may run flawlessly on Linux but not on Windows, and vice versa. Before integrating them into your code, test them on all platforms.

The following are some of the methods for obtaining a hostname:

  • Socket gethostname function
  • Platform module
  • Os module
  • Using socket gethostbyaddr function

Using the socket gethostname function

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import socket
print(socket.gethostname())</pre>
</div>

One of the most significant networking modules in Python is the socket module. Sockets can be used to communicate and connect to other devices. In the above example, we first imported the socket module and then used the function gethostname() to retrieve the device’s Hostname. The device hostname where the python code is interpreted will be returned by this method.

Using the platform module

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import platform
print(platform.node())</pre>
</div>

The platform module is commonly used to obtain information like the socket module. This data contains hostnames, IP addresses, operating systems, etc. In the first line, we imported the platform and then used the node() function to acquire the device’s hostname. If the computer hostname is available, the node function returns it.

Using the OS module

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import os, platform

if platform.system() == "Windows":
  print(platform.uname().node)
else:
  print(os.uname()[1])</pre>
</div>

The os module is commonly used in Python to handle files and directories, but it may also be used to obtain the device name. The system’s hostname is returned by the function uname(). Unfortunately, this isn’t compatible with Windows devices, and you’ll need to add an if clause to make it work.

Employing the socket gethostbyaddr function

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import socket
print(socket.gethostbyaddr(socket.gethostname())[0])</pre>
</div>

The hostnames linked to their IPs will be taken care of by gethostbyaddr. On a local network, it will usually return the same hostname supplied as a parameter. Still, it can return the remote hostnames (as discussed in the following sections).

Getting the hostname from the URL in Python

You’ll often need to access domain names using URLs you already have. Regex, urllib, string splitting, and other Python tools can do this. They all function most of the time, but urllib is the best choice because it comes from the networking module and is installed by default. As a result, you won’t need to write any complicated code.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>from urllib.parse import urlparse

url = urlparse('https://thirdeyemedia.wpmudev.host/codeunderscored/python-set-update-explained-with-examples/' )

host = '{uri.scheme}://{uri.netloc}/'.format(uri=url)

print(host)</pre>
</div>

To begin, we need to import urlparse from the urllib parser. It can be used to parse URLs into strings that can be understood. When we give urlparse() a URL to parse, it breaks it down into scheme, netloc, params, query, and fragment. The protocol and hostnames can then be extracted from the URL using scheme and netlock.

Getting the hostname from the IP address in Python

In some cases, the IP addresses appear in the code results. The hostnames of the servers can then be deduced using them. However, your IP address must be operational and reachable via your network. In the example below, I’ve used 8.8.8.8 as the IP address, which is Google’s DNS.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import socket
print(socket.gethostbyaddr("8.8.8.8"))</pre>
</div>

The first steps are to import the socket module and then perform the gethostbyaddr function. Also, the IP address can then be passed to it as a string. It returns (hostname, alias list, IP Address List) as a tuple. The hostname can then be accessed via tuple indexing.

How to get the IP address in Python

A local machine’s hostname and IP address can be found in various methods. Using python code, here’s a quick way to retrieve the hostname and IP address. The BSD socket interface is accessible through the socket module. It runs on all current Unix systems and Windows, macOS, and maybe more platforms.

Python has two functions: gethostname() and gethostbyname(). First, the gethostname() returns the local machine’s standard hostname. On the other hand, gethostbyname() retrieves host information from a host database based on a hostname.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>Socket.gethostname()
Socket.gethostbyname()</pre>
</div>

The algorithm

Step 1: The first step is to use a module socket.

Step 2: gethostname() returns the local machine’s standard hostname.

Step 3: gethostbyname() retrieves host information from a host database corresponding to a hostname.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># How to show the hostname and IP address

import socket

def show_hostname_ip():
   try:
      host_name = socket.gethostname()
      host_ip_address = socket.gethostbyname(host_name)
      print(" The hostname is :  ",host_name )
      print("The host IP Address: ",host_ip_address)
   except:
      print(" Cannot get Hostname and IP Address")

# Function call
show_hostname_ip()
</pre>
</div>

Code breakdown

According to the code above, our socket module is imported in the first line. We then declare the name of the function as show_hostname_ip. What follows is surrounding the actual functionality within the try and except to avoid the function coming to a specific halt when executing without proper notification.

Within the actual function, we get the hostname using the socket method gethostname(). The gethostname() is a method that returns the hostname of a computer.

The following line retrieves host information from a host database corresponding to the hostname above. The final two lines are used to print the info retrieved above.

Conclusion

In this post, we’ve looked at using the Python programming language to display the hostname and IP address. Recall that Python has two functions: gethostname() and gethostbyname(). gethostname() returns the local machine’s standard hostname. In addition, gethostbyname() retrieves host information from a host database based on a hostname.

Similar Posts

Leave a Reply

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