Python Program to get IP Address of your Computer
Hello Coder! In this article, we will learn to write a Python program to get the IP Address of our computer.
Let us know more about the IP Address before getting into the program.
IP Address
IP Address stands for Internet Protocol Address.
IP Address is a unique identifier that is used to identify a device on the internet or a local network.
There are two versions of defining IP Address. IPv4 and IPv6. IPv4 defines IP Address as a 32-bit number. IPv6 defines an IP Address as a 128-bit number.
Example for IPv4 Address: 172.15.254.1.
Example for IPv6 Address: 2000:0db8:85a3:0000:0000:8a2e:0370:7334
In this article, we are going to obtain IP Address of our computer using the socket library.
We are going to make use of the method gethostbyname() in socket library to get the IP Address of our computer. It takes hostname as its argument and returns the IPv4 Address of the host.
Program
Now it is time to get the IP Address of your Computer with the help of a Python program.
Let us first import the socket module to make use of the method gethostbyname() in socket library.
import socket
For getting the IP Address of the host, we need to pass hostname as the parameter to gethostbyname(). So let us get the hostname of our computer using gethostname() method and pass it as a parameter to gethostbyname() to get the IP Address.
Also, assign the returned value of the gethostbyname() method to the variable.
IP_Address = socket.gethostbyname(socket.gethostname())
Let us the now print the IP Address using a print statement.
print("IP Address of your computer is : ", IP_Address)
Output
IP Address of your computer is : 192.168.56.2
Yahoo! We have successfully obtained the IP Address of our computer using a simple snippet in Python.
Thanks for reading the article. I hope this article helped you in some way. Also, do check out our other articles below:
Leave a Reply