Skip to content

Commit

Permalink
Support IP address host in req.subdomains
Browse files Browse the repository at this point in the history
fixes #2308
  • Loading branch information
dougwilson committed Sep 9, 2014
1 parent d07c063 commit 2de6514
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
1 change: 1 addition & 0 deletions History.md
Expand Up @@ -2,6 +2,7 @@
===

* Support `X-Forwarded-Host` in `req.subdomains`
* Support IP address host in `req.subdomains`
* deps: connect@2.26.0
- deps: body-parser@~1.8.1
- deps: compression@~1.1.0
Expand Down
5 changes: 4 additions & 1 deletion lib/request.js
Expand Up @@ -13,6 +13,7 @@ var http = require('http')
, parse = require('parseurl')
, proxyaddr = require('proxy-addr')
, mime = connect.mime;
var isIP = require('net').isIP;

/**
* Request prototype.
Expand Down Expand Up @@ -454,7 +455,9 @@ req.__defineGetter__('auth', function(){
req.__defineGetter__('subdomains', function(){
var host = this.host;
var offset = this.app.get('subdomain offset');
var subdomains = host.split('.').reverse();
var subdomains = !isIP(host)
? host.split('.').reverse()
: [host];

return subdomains.slice(offset);
});
Expand Down
54 changes: 54 additions & 0 deletions test/req.subdomains.js
Expand Up @@ -17,6 +17,32 @@ describe('req', function(){
.set('Host', 'tobi.ferrets.example.com')
.expect(["ferrets","tobi"], done);
})

it('should work with IPv4 address', function(done){
var app = express();

app.use(function(req, res){
res.send(req.subdomains);
});

request(app)
.get('/')
.set('Host', '127.0.0.1')
.expect([], done);
})

it('should work with IPv6 address', function(done){
var app = express();

app.use(function(req, res){
res.send(req.subdomains);
});

request(app)
.get('/')
.set('Host', '[::1]')
.expect([], done);
})
})

describe('otherwise', function(){
Expand Down Expand Up @@ -80,6 +106,34 @@ describe('req', function(){
.set('Host', 'tobi.ferrets.sub.example.com')
.expect(["com","example","sub","ferrets","tobi"], done);
})

it('should return an array with the whole IPv4', function (done) {
var app = express();
app.set('subdomain offset', 0);

app.use(function(req, res){
res.send(req.subdomains);
});

request(app)
.get('/')
.set('Host', '127.0.0.1')
.expect(['127.0.0.1'], done);
})

it('should return an array with the whole IPv6', function (done) {
var app = express();
app.set('subdomain offset', 0);

app.use(function(req, res){
res.send(req.subdomains);
});

request(app)
.get('/')
.set('Host', '[::1]')
.expect(['[::1]'], done);
})
})

describe('when present', function(){
Expand Down

0 comments on commit 2de6514

Please sign in to comment.