6.0 KiB
6.0 KiB
GetIPDataView Documentation
📄 File Location
api/views/GetIPDataView.py
Overview
Retrieves client IP address information from various HTTP headers and server variables. This view provides comprehensive IP address detection for logging, analytics, and security purposes.
Class Details
@permission_classes([AllowAny])
class GetIPDataView(APIView):
def get(self, request):
# Implementation...
Permissions
- Access Level: Public (no authentication required)
- Authentication: None (
@permission_classes([AllowAny]))
Method Details
GET /api/get-ip-data/
Description
Extracts and returns client IP address information from multiple sources including direct connection, proxy headers, and load balancer information.
Parameters
No parameters required.
Response Format
{
"ip_info": {
"remote_addr": "string",
"http_x_forwarded_for": "string",
"http_x_real_ip": "string",
"http_client_ip": "string",
"http_x_forwarded": "string",
"http_x_cluster_client_ip": "string",
"http_forwarded_for": "string",
"http_forwarded": "string"
}
}
Response Field Descriptions
| Field | Type | Description |
|---|---|---|
remote_addr |
string | Direct connection IP address |
http_x_forwarded_for |
string | Comma-separated list of IP addresses from proxy chain |
http_x_real_ip |
string | Real client IP as seen by reverse proxy |
http_client_ip |
string | Client IP from custom header |
http_x_forwarded |
string | Forwarded header value |
http_x_cluster_client_ip |
string | Cluster client IP header value |
http_forwarded_for |
string | Standard forwarded for header |
http_forwarded |
string | Standard forwarded header |
Usage Examples
Basic Usage:
curl -X GET http://your-api.com/api/get-ip-data/
Expected Response:
{
"ip_info": {
"remote_addr": "192.168.1.100",
"http_x_forwarded_for": "203.0.113.50, 198.51.100.25",
"http_x_real_ip": "203.0.113.50",
"http_client_ip": "",
"http_x_forwarded": "",
"http_x_cluster_client_ip": "",
"http_forwarded_for": "",
"http_forwarded": ""
}
}
Empty Response Example:
{
"ip_info": {
"remote_addr": "",
"http_x_forwarded_for": "",
"http_x_real_ip": "",
"http_client_ip": "",
"http_x_forwarded": "",
"http_x_cluster_client_ip": "",
"http_forwarded_for": "",
"http_forwarded": ""
}
}
Error Handling
Status Codes
- 200 OK: Request successful, returns IP information
- No explicit error handling: Missing headers return empty strings rather than errors
Behavior with Missing Headers
When a specific IP header is not present:
- Returns an empty string (
"") for that field - Does not raise exceptions or return error responses
- All fields are always present in the response
Implementation Details
Code Analysis
def get(self, request):
ip_info = {
'remote_addr': request.META.get('REMOTE_ADDR'),
'http_x_forwarded_for': request.META.get('HTTP_X_FORWARDED_FOR'),
# ... other headers
}
return Response({"ip_info": ip_info}, status=status.HTTP_200_OK)
Key Features
- ✅ Non-intrusive: No side effects on request processing
- ✅ Comprehensive: Checks multiple IP source headers
- ✅ Safe: Gracefully handles missing headers
- ✅ Public access: No authentication required
- ✅ Lightweight: Minimal processing overhead
Use Cases
Security & Analytics
- Log visitor IP addresses for security monitoring
- Track user location patterns
- Detect suspicious activity
Load Balancer Integration
- Extract original client IP behind proxies
- Support for cloud platforms (AWS, GCP, Azure)
- Works with CDN configurations
Debugging & Development
- Verify client connection details
- Test proxy configurations
- Debug network routing issues
⚠️ Important Notes
Header Priority
The view checks headers in this order (first found takes precedence):
REMOTE_ADDR(most reliable)X-Forwarded-ForX-Real-IPClient-IpX-ForwardedX-Cluster-Client-IPForwarded-ForForwarded
Security Considerations
- Trust Level: Be cautious when trusting forwarded headers in production
- Validation: Consider validating IP addresses before use
- Privacy: Ensure compliance with data protection regulations
Performance Impact
- Minimal: Only reads existing request metadata
- No external calls: Pure local operation
- Constant time: O(1) complexity regardless of header count
Integration Examples
Python Client
import requests
response = requests.get('http://api.example.com/api/get-ip-data/')
if response.status_code == 200:
ip_data = response.json()
print(f"Client IP: {ip_data['ip_info']['remote_addr']}")
JavaScript Frontend
fetch('/api/get-ip-data/')
.then(response => response.json())
.then(data => {
console.log('IP Info:', data.ip_info);
});
Django View Integration
from django.http import JsonResponse
def some_view(request):
ip_view = GetIPDataView()
ip_response = ip_view.get(request)
# Process IP data as needed
Testing
Test Cases
- Direct Connection: Test without any proxy headers
- Single Proxy: Test with X-Forwarded-For header
- Multiple Proxies: Test with comma-separated IPs
- Mixed Headers: Test with various header combinations
- Missing Headers: Test with no relevant headers
Expected Behavior
- Always returns 200 status code
- Always includes all 8 IP info fields
- Empty strings for unavailable headers
- No exceptions or error responses
Last Updated: Current Session Version: 1.0