Blog | G5 Cyber Security

Get User IP Address

TL;DR

Getting a user’s IP address reliably is tricky due to privacy and security measures. The best approach depends on where you need the IP (server-side vs client-side) and what you’re using it for. Server-side methods are more accurate, but require control of the server. Client-side relies on external services and can be bypassed.

1. Understanding IP Addresses

An IP address is a unique number that identifies a device on a network (like the internet). There are two main types you’ll encounter:

2. Server-Side Methods (Most Reliable)

If you control the server handling requests from users, this is the preferred way to get their IP address.

2.1 Using Request Headers

  1. Identify the Header: Common headers that might contain the IP include X-Forwarded-For, X-Real-IP, and Remote_Addr. The specific header depends on your server setup (e.g., Apache, Nginx, Node.js).
  2. Access the Header: How you access this varies by language/framework.
    • PHP:
    • Node.js (Express):
      const ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
      console.log(ipAddress);
      
    • Python (Flask):
      from flask import request
      ip_address = request.remote_addr
      print(ip_address)
  3. Important: Always check for and handle X-Forwarded-For carefully, as it can be spoofed by users. Validate the IP address format before using it.

3. Client-Side Methods (Less Reliable)

Client-side methods rely on external services and are more prone to inaccuracies or being blocked.

3.1 Using Third-Party APIs

  1. Choose an API: Services like ipify, icanhazip, and others provide APIs that return the user’s public IP address.
  2. Make a Request: Use JavaScript to make an HTTP request to the API endpoint.
    fetch('https://api.ipify.org?format=json')
      .then(response => response.json())
      .then(data => {
        const ipAddress = data.ip;
        console.log(ipAddress);
      })
      .catch(error => console.error('Error:', error));
  3. Limitations: These APIs can be blocked by firewalls or privacy extensions. They also rely on the user’s browser making a request, which isn’t always guaranteed.

4. Considerations and Best Practices

Exit mobile version