Finding IP Address using Python
An IP(Internet Protocol) address is an identifier assigned to each computer and other device(e.g., router, mobile, etc.) connected to a TCP/IP network that is used to locate and identify the node in communication with other nodes on the network. IP addresses are usually written and displayed in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP address).
Using the socket library to find IP Address
Step 1: Import socket library
IPAddr = socket.gethostbyname(hostname)
Step 2: Then print the value of the IP into the print() function your IP address.
print("Your Computer IP Address is:" + IPAddr)
Below is the complete Implementation:
Here we have to import the socket first then we get the hostname by using the gethostname() function and then we fetch the IP address using the hostname that we fetched and the we simply print it.
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)
Output
Your Computer Name is:pppContainer
Your Computer IP Address is:10.98.162.168
Explanation:
- socket.gethostname() retrieves your computer's name (hostname).
- socket.gethostbyname(hostname) gets the corresponding IP address of that hostname.
Using the os module to find IP Address
Here we are using the os module to find the system configuration which contains the IPv4 address as well.
import os
print(os.system('ipconfig'))
Output

Explanation:
- os.system('ipconfig') runs the ipconfig command in the system shell (Windows only). This command displays network configuration, including IP addresses.
- os.system() returns the exit status code of the command, not its output.
- print(os.system(...)) will show the entire ipconfig output in the console and then print the exit code (usually 0 if successful).
Using the request module to find IP Address
Here we are using the request module of Python to fetch the IP address of the system.
from urllib.request import urlopen
import re as r
def getIP():
d = str(urlopen('http://checkip.dyndns.com/')
.read())
return r.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').
search(d).group(1)
print(getIP())
Output
103.251.142.122
Explanation:
- This code sends an HTTP request to
http://checkip.dyndns.com/
, which returns a web page containing your public IP address. - The response is a string like
"Current IP Address: 203.0.113.45"
. - A regular expression (
re
) is used to extract the IP address from the string. Finally, it prints the public IP address.
Related Post: Java program to find IP address of your computer