Created
May 12, 2023 17:19
-
-
Save RyadPasha/e1777d7f72d2dafb57269ba3d631c88c to your computer and use it in GitHub Desktop.
Retrieve the real IP address of the user making the request.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Real User IP Grabber | |
* | |
* @author Mohamed Riyad <m@ryad.me> | |
* @link RyadPasha.com | |
* @copyright Copyright (C) 2022 RyadPasha. All rights reserved. | |
* @license GNU General Public License v3.0 http://www.gnu.org/copyleft/gpl.html | |
* @version Release: 1.0 | |
* @since 10 Nov, 2022 | |
*/ | |
/** | |
* Retrieve the real IP address of the user making the request. | |
* Supports various IP address sources including CloudFlare proxy, | |
* `x-forwarded-for` header, `x-real-ip` header, and remote address from the socket or connection. | |
* | |
* @param {Object} req - The request object representing the incoming HTTP request. | |
* @returns {string} The real IP address of the user. | |
* @author Mohamed Riyad <m@ryad.me> | |
* @since 10 Nov, 2022 | |
* @updated 12 May, 2023 | |
*/ | |
const getRealUserIP = (req) => { | |
const headers = req.headers | |
// Prefer `cf-connecting-ip` header (CloudFlare proxy) | |
if (headers['cf-connecting-ip']) { | |
return headers['cf-connecting-ip'] | |
} | |
// Check `x-forwarded-for` header | |
const forwardedFor = headers['x-forwarded-for'] | |
if (forwardedFor) { | |
// The x-forwarded-for header can contain a comma-separated list of IP's. | |
// Extract the first IP address. | |
return forwardedFor.split(',')[0].trim() | |
} | |
// Check `x-real-ip` header | |
if (headers['x-real-ip']) { | |
return headers['x-real-ip'] | |
} | |
// Fallback to retrieving remote address from `req.socket` | |
if (req.socket && req.socket.remoteAddress) { | |
return req.socket.remoteAddress | |
} | |
// Or from the deprecated `req.connection` | |
if (req.connection && req.connection.remoteAddress) { | |
return req.connection.remoteAddress | |
} | |
// If all else fails, return an empty string | |
return '' | |
} | |
module.exports = getRealUserIP |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment