Python program to Display Hostname and IP address?

In this article, we are going to learn how to display the hostname and IP address. Generally, the devices that connect to a network are identified by two things:

  • Hostname: It is the name assigned to the device on a network. It helps users to identify devices in a human-readable format (e.g, mypc, desktop-pc, etc.)
  • IP Address: It is the numerical address assigned to each device on a network, used to locate and communicate with that device.

Python provides the built-in socket module for achieving this task, which provides access to various network-related functionalities.

Using socket.gethostname() Function

The Python socket.gethostname() function is part of the socket module used to retrieve the hostname of the current device on which the Python script is running.

Syntax

Following is the syntax of the Python socket.gethostname() function ?

import socket
hostname = socket.gethostname()

Using socket.gethostbyname() Function

The socket.gethostbyname() function is used to find the IP address of the website or the device using its hostname.

Syntax

Following is the syntax of the Python socket.gethostbyname() function ?

ip_address = socket.gethostbyname(hostname)

Example 1: Display Local Hostname and IP Address

Let's look at the following example, where we are going to display the hostname and ip address of the current device ?

import socket

hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)

print("Hostname:", hostname)
print("IP Address:", ip_address)

The output of the above program is as follows ?

Hostname: 5ce401f863e8
IP Address: 172.18.0.2

Example 2: Get IP Address of a Website

In this scenario, we are going to consider another website and pass it as an argument to the socket.gethostbyname() for getting the IP address ?

import socket

website = "www.tutorialspoint.com"
ip_address = socket.gethostbyname(website)

print("Website:", website)
print("IP Address:", ip_address)

The output of the above program is as follows ?

Website: www.tutorialspoint.com
IP Address: 18.165.121.16

Getting Full Host Information

You can also retrieve more detailed information about a host using socket.gethostbyname_ex() ?

import socket

hostname = socket.gethostname()
host_info = socket.gethostbyname_ex(hostname)

print("Hostname:", host_info[0])
print("Aliases:", host_info[1])
print("IP Addresses:", host_info[2])

The output shows detailed host information ?

Hostname: 5ce401f863e8
Aliases: []
IP Addresses: ['172.18.0.2']

Conclusion

The socket module provides simple functions to retrieve hostname and IP address information. Use gethostname() to get the local hostname and gethostbyname() to resolve hostnames to IP addresses.

Updated on: 2026-03-24T21:00:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements