Python get visitor information by IP address
In this post, you will learn how to get visitor full information, like Country, State, Region, Timezone, Latitude, Longitude and so on, using the visitor's IP address in Python programming language.
IP stands for "Internet Protocol", which is the set of rules governing the format of data sent via the internet or local network. An IP address is a unique address that identifies a device on the internet or a local network.
The site visitor's information is so important. By using this, you can easily know about the geographical locations of users. You can also show or hide the visitors from particular countries. You can also store visitor's information in the database to make your own analytics report.
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.
import socket
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
Python urllib package
We also need the json module to convert the data in JSON format and urllib package to collect its module for working with urls. In this article, we have used the following modules-
urllib.request- for opening and reading urls.
urllib.parse- for parsing urls
urllib.error- containing the exceptions.
Complete Code: Python get visitor information by IP address
Here is the complete Python code to get current visitor information by IP address. We are using the 'geoplugin' API. The information received by the third party is not more readable. So, we have decoded them using the decode() function.
import urllib.request, urllib.parse, urllib.error
import json, socket
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
serviceurl = 'http://www.geoplugin.net/json.gp?ip='+host_ip
print('Retrieving', serviceurl)
uh = urllib.request.urlopen(serviceurl)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
js = json.loads(data)
print(data)
Output of the above code:
Related Articles
Python convert list to numpy arrayPython Numpy Array Shape
Python NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Trigonometric functions Python Numpy
CRUD operations in Python using MongoDB connector
Write Python Pandas Dataframe to CSV
Quick Introduction to Python Pandas
Python Pandas DataFrame
Python3 Tkinter Messagebox
Python Tkinter Geometry Managers
Python Tkinter Scale Widget
Python Tkinter Overview and Examples
Python Turtle Graphics Overview
Factorial Program in Python
Python snake game code with Pygame
Python JSON Tutorial - Create, Read, Parse JSON file
Python convert xml to dict
Python convert dict to xml