
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Let's look at the following example, where we are going to display the hostname and ip address of the current device.
import socket x = socket.gethostname() y = socket.gethostbyname(x) print("Hostname:", x) print("IP Address:", y)
The output of the above program is as follows -
Hostname: 5ce401f863e8 IP Address: 172.18.0.2
Example 2
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 x = "www.tutorialspoint.com" y = socket.gethostbyname(x) print("Website:", x) print("IP Address:", y)
The output of the above program is as follows -
Website: www.tutorialspoint.com IP Address: 18.165.121.16