Display Hostname and IP address in Python

There are many ways to find hostname and IP address of a local machine. Here is a simple method 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 probably additional platforms.

Method used :

  • gethostname() : The gethostname function retrieves the standard host name for the local computer.
  • gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database.
# Python3 code to display hostname and
# IP address

# Importing socket library
import socket

# Function to display 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 conributed by "Sharad_Bhardwaj".

Output:

Hostname :   pppContainer
IP :  10.98.162.168

NOTE : Output varies machine to machine.

This article is contributed by Sharad_Bhardwaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.