Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to find the IP Address of the client
In this tutorial, we are going to find the IP address of the client using the socket module in Python. Every laptop, mobile, tablet, etc., has their unique IP address. We will find it by using the socket module. Let's see the steps to find out the IP address of a device.
Algorithm
- Import the
socketmodule. - Get the hostname using the
socket.gethostname()method and store it in a variable. - Find the IP address by passing the hostname as an argument to the
socket.gethostbyname()method and store it in a variable. - Print the IP address.
Let's write code for the above algorithm.
Example
# importing socket module
import socket
# getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
# getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
# printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
If you run the above program, you will get the following output ?
Hostname: DESKTOP-A0PM5GD IP Address: 192.168.43.15
Alternative Method Using External Service
The above method gives you the local IP address. To find your public IP address, you can use external services ?
import socket
import requests
# Get local IP
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
# Get public IP
public_ip = requests.get('https://api.ipify.org').text
print(f"Local IP: {local_ip}")
print(f"Public IP: {public_ip}")
Key Points
-
socket.gethostname()returns the machine's hostname -
socket.gethostbyname()resolves hostname to IP address - This method returns the local network IP address
- For public IP detection, external services are required
Conclusion
The socket module provides a simple way to find the local IP address of your machine. Use gethostname() and gethostbyname() methods to retrieve hostname and corresponding IP address respectively.
Advertisements
