Change language

Show hostname and IP address in Python

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.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method