There are many ways to find the hostname and IP address of a local machine. Here is a simple method to find the 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 in Python.
Get Hostname in Python
Method 1: Using the Platform module
The Platform module is used to retrieve as much possible information about the platform on which the program is being currently executed. platform.node() function returns a string that displays the information about the node basically the system’s network name.
Python3
import platform print (platform.node()) |
Output:
GFGNDASM444
Method 2: Using Socket module
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The gethostname function retrieves the standard host name for the local computer.
Python3
import socket print (socket.gethostname()) |
Output:
GFGNDASM444
Get IP address in Python
Method 1: Using socket.gethostbyname
The gethostbyname function retrieves host information corresponding to a hostname from a host database.
Python3
import socket print (socket.gethostbyname(socket.gethostname())) |
Output:
10.143.90.178
Method 2: Using socket.socket instance
Here, two parameters were supplied to a socket instance that was created. AF INET is the first parameter, while SOCK STREAM is the second. AF INET stands for ipv4 address-family. The connection-oriented TCP protocol is referred to as SOCK STREAM.
Python3
import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # connect() for UDP doesn't send packets s.connect(( '10.0.0.0' , 0 )) print (s.getsockname()[ 0 ]) |
Output:
10.143.90.178
Display Hostname and IP address in Python
We are using the same code which is explained above. Here we compile the hostname and IP address in one program.
Python3
# 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 contributed by "Sharad_Bhardwaj". |
Output:
Hostname : pppContainer IP : 10.98.162.168 NOTE: Output varies from machine to machine.