python program to find IP address and host name

In this article, we will find IP address and Host name in python using socket.

First, we install the sockets Python library by using pip install sockets command typed in our python terminal. After installing Sockets we are importing the socket in our program by using import socket just like other libraries.

Here we will use, socket.gethostname() which gets hostname and it will store in variable. Same as socket.gethostname(hostname) for IP address.

Example :

    
#python program to get hostname and ip address in python
import socket 

hostname = socket.gethostname() 
ip_address = socket.gethostbyname(hostname) 

print("Your HostName is: ",hostname) 
print("Your IP Address is: ",ip_address)
       

Output :

    
Your HostName is:  LAPTOP-M4EEHVNS
Your IP Address is:  192.168.43.155
    

This above example, first it will find host name and then it will find IP address using host name.


Share your thoughts

Ask anything about this examples