Skip to content

Instantly share code, notes, and snippets.

@pcdinh
Forked from 3rd-Eden/remote.js
Created May 30, 2013 13:09
Show Gist options
  • Save pcdinh/5677698 to your computer and use it in GitHub Desktop.
Save pcdinh/5677698 to your computer and use it in GitHub Desktop.
var http = require('http')
, request = http.IncomingMessage.prototype;
/**
* Add a uniform interface for remote address in Node.js
*
* @api private
*/
request.__defineGetter__('remote', function remote () {
var connection = this.connection
, headers = this.headers
, socket = connection.socket;
// return early if we are behind a reverse proxy
if (headers['x-forwarded-for']) {
return {
ip: headers['x-forwarded-for']
, port: headers['x-forwarded-port']
}
}
// regular HTTP servers
if (connection.remoteAddress) {
return {
ip: connection.remoteAddress
, port: connection.remotePort
};
}
// in node 0.4 the remote address for https servers was in a different
// location
if (socket.remoteAddress) {
return {
ip: socket.remoteAddress
, port: socket.remotePort
};
}
// last possible location..
return {
ip: this.socket.remoteAddress || '0.0.0.0'
, port: this.socket.remotePort || 0
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment