Guides
Last updated
January 27, 2021

How to get a user’s IP address in Python

Emma Jagger
Emma Jagger

Table of Contents:

Get your free
IP Geolocation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Because an IP address uniquely identifies every machine on a network, user IP addresses provide a useful way to track new and repeat visitors to your platform. Additionally, geolocating an IP address provides a way to obtain information on a user's real-world location. This information can be used to improve your marketing by incorporating targeted advertisements and to improve the user experience by customizing your platform to their location.

This blog post covers how to identify a user's IP address using Python. If you just want to identify your own, use our tool to see what is your IP address and location.

Get an IP address in Python using the network socket interface

One way to obtain a user's IP address is by using Python's native low-level networking interface, socket. A user's IP address can be obtained by querying the device's host name and then getting the associated IP address:



import socket

# get the hostname of the socket
hostname = socket.gethostname()
# get the IP address of the hostname
ip_address = socket.gethostbyname(hostname)
print('IP Address:{}'.format(ip_address))

Drawbacks to using sockets to get IP addresses in Python

The primary drawback of this method is that its behavior may be platform dependent, since it relies on the operating system's socket APIs. Although it is available on all modern Windows, MacOS, and Unix systems, this method may not work for older operating systems. Additionally, this approach may not work for devices that operate on less common platforms.

This approach also only provides the device's IP address without any additional information from the IP. Although this data can be used to identify unique visitors to a platform, obtaining information about a user's location or Internet provider requires queries to external databases.

Enter an IP address to start
Need inspiration? Try
73.162.0.1
VALIDATE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Checking
5
Results for
ip address
Country:
TEST
Region:
TEST
City:
TEST
Coordinates:
TEST
Zip code:
TEST
Connection:
TEST
Get free credits, more data, and faster results

Get an IP address in Python using Abstract's Geolocation API

Abstract API offers a free geolocation API that obtains a user's IP address and provides associated location information. A query to this API also provides information relevant to the user's location, such as their timezone, currency, and regional flag. This information makes it possible to customize the user experience across your platform with just a single data call.

To obtain a user's IP address and its associated location info, we can perform a simple call to Abstract's Geolocation API:



import requests
import json

# Your API key, available from your account page
YOUR_GEOLOCATION_KEY = 'your_key'

# URL to send the request to
request_url = 'https://ipgeolocation.abstractapi.com/v1/?api_key=' + YOUR_GEOLOCATION_KEY
response = requests.get(request_url)
result = json.loads(response.content)
print(result)
print('ip_address: {}'.format(result['ip_address']))

This approach provides a variety of geolocation information in addition to the user's IP address. If this data was requested for a user with the IP address 139.130.4.5, the call would return the following information:



{
'ip_address': '139.130.4.5',
'city': 'Sydney',
'city_geoname_id': 2147714,
'region': 'New South Wales',
'region_iso_code': 'NSW',
'region_geoname_id': 2155400,
'postal_code': '1001',
'country': 'Australia',
'country_code': 'AU',
'country_geoname_id': 2077456,
'country_is_eu': False,
'continent': 'Oceania',
'continent_code': 'OC',
'continent_geoname_id': 6255151,
'longitude': 151.209,
'latitude': -33.8688,
'security': {
'is_vpn': False
},
'timezone': {
'name': 'Australia/Sydney',
'abbreviation': 'AEDT',
'gmt_offset': 11,
'current_time': '12:17:29',
'is_dst': True
},
'flag': {
'emoji': '🇦🇺',
'unicode': 'U+1F1E6 U+1F1FA',
'png': 'https://static.abstractapi.com/country-flags/AU_flag.png',
'svg': 'https://static.abstractapi.com/country-flags/AU_flag.svg'
},
'currency': {
'currency_name': 'Australian Dollars',
'currency_code': 'AUD'
},
'connection': {
'autonomous_system_number': 1221,
'autonomous_system_organization': 'Telstra Corporation',
'connection_type': 'Corporate',
'isp_name': 'Telstra Internet',
'organization_name': None
}
}

Frequently Asked Questions

What is the simplest way to get an IP address in Python?

The simplest method uses Python's built-in socket module. You call socket.gethostname() to get the machine's hostname, then pass that to socket.gethostbyname() to retrieve the associated IP address. No third-party libraries are required, but this approach is platform dependent and may not behave consistently on all operating systems.

What is the difference between using the socket module and an IP geolocation API?

The socket module returns only a raw IP address with no additional context. An IP geolocation API like Abstract's returns enriched data including country, city, timezone, currency, and security signals such as VPN or proxy detection. If you need location-based personalization or security checks, an API is the more practical choice.

How do I get a visitor's IP address in a Python web application?

In a web framework such as Flask, you access the client's IP via request.remote_addr. If your app sits behind a proxy or load balancer, you should also check request.environ.get('HTTP_X_FORWARDED_FOR'), since the forwarded header carries the original client IP rather than the proxy's address.

Why does the socket method sometimes return 127.0.0.1 or a local address?

The socket module resolves the hostname of the machine running your Python script, not the public-facing IP of a remote user. On some systems, the hostname resolves to the loopback address (127.0.0.1). This method is only suitable for finding the local machine's IP, not for identifying visitors to a web service.

How do I turn an IP address into location data in Python?

Once you have an IP address, you can pass it to a geolocation API using the requests library. Send a GET request with the IP and your API key, then parse the JSON response to extract fields like country, city, and timezone. Abstract's IP Geolocation API returns all of these in a single call.

Why is the requests library used alongside the socket module in Python IP lookup examples?

The socket module handles low-level network queries to find a machine's IP, while the requests library is used to make HTTP calls to external APIs. In a typical workflow, you might use socket to retrieve an IP and then use requests to send that IP to a geolocation API and get back structured location data via JSON.

Emma Jagger
Emma Jagger

Emma Jagger is an experienced engineer and Google alumna with a degree from Carnegie Mellon University. She specializes in email validation, IP geolocation, and API integration, focusing on creating practical and scalable solutions through her technical writing.

Get your free
IP Geolocation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
IP Geolocation
key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required