Show hostname and IP address in Python

Python Methods and Functions

There are many ways to find the hostname and IP address of the local machine. Here is an easy way to find hostname and IP address using Python code. 
Library used —  socket : This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, MacOS and possibly additional platforms. 

Method used:

  • gethostname () : The gethostname function retrieves the default hostname for the local computer.
  • gethostbyname () : The gethostbyname function retrieves the hostname information corresponding to the hostname from the host database.

# Python3 code to display hostname and
# IP address

 
# Socket library import

import socket

 
# Function for displaying hostname and
# IP address

def get_Host_name_IP ():

  try :

host_name = socket.gethostname ()

host_ip = socket.gethostbyname (host_name)

print ( "Hostname: " , host_name)

print ( "IP:" , host_ip)

except :

print ( "Unable to get Hostname and IP" )

 
# Driver code

get_Host_name_IP () # Function call

 
# This code is provided by Sharad_Bhardwaj.

Output:

 Hostname: pppContainer IP: 10.98.162.168 

NOTE . Power depends on the machine.





Tutorials