How To Find IP Address In Python
In this post, you will learn how to find the IP address using the Python programming language.
IP (Internet Protocol) addresses are used to identify hardware devices on a network. It is a unique address that identifies a device on the internet or a local network. The internet needs a way to differentiate between different computers, routers, and websites. IP addresses give an approach to doing so and form an essential part of how the internet works. Here, we are going to find the IP address of the client using the socket module in Python.
Python Socket
A socket is one endpoint of two communication links. An endpoint is a combination of an IP address and a port number. So first, we need a socket module to get the current visitor's IP address. This module provides the gethostname() and gethostbyname() methods to get the visitor's hostname and IP address respectively.
Python program to find the IP Address of the client
In the given program, first we import the socket module. Then, we use the socket.gethostname() method to get the hostname and store it in a variable. We pass this hostname as an argument to the socket.gethostbyname() method and find the IP address.
# Importing socket module
import socket
# Getting the hostname
hostname = socket.gethostname()
# Getting the IP address
ip_address = socket.gethostbyname(hostname)
# Printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
Output of the above code:
Hostname: repl-app-5586c4b874-7k8f8
IP Address: 10.244.50.234
Related Articles
Python get visitor information by IP addressConvert MySQL query result to JSON in Python
Insert JSON data into MongoDB using Python
Convert MongoDB Document to JSON using Python
Python read JSON from URL requests
Python convert XML to JSON
Convert JSON to CSV using Python
Python JSON Tutorial - Create, Read, Parse JSON
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml