发出IPv4请求IP使用IPv4表示法而不是IPv6

时间:2017-01-29 04:20:38

标签: javascript node.js express

快递provides the request IP address via req.ip(其中req是请求),但对于IPv4地址,它使用IPv6 notation,例如:

::ffff:1.2.3.4

我很高兴它支持IPv6并没有大惊小怪,但出于用户界面的目的,我希望以IPv4表示法显示IPv4地址(" 1.2.3.4")当然,仍然保持对IPv6地址的支持。

我可以让Express为IPv4请求地址使用纯IPv4表示法吗?

1 个答案:

答案 0 :(得分:2)

好吧,我找到了一种使用ipaddr.js module的方法,我通过this answer找到了这个方法。该模块可用于检查IPv6地址是否为IPv4地址,然后进行转换。例如:

var ip = require('ipaddr.js')

function cleanupAddress (str) {
    // if it's a valid ipv6 address, and if its a mapped ipv4 address,
    // then clean it up. otherwise return the original string.
    if (ip.IPv6.isValid(str)) {
        var addr = ip.IPv6.parse(str);
        if (addr.isIPv4MappedAddress())
            return addr.toIPv4Address().toString();
    }
    return str
}

console.log(cleanupAddress('1.2.3.4'));
console.log(cleanupAddress('::ffff:1.2.3.4'));
console.log(cleanupAddress('::ffff:102:304'));
console.log(cleanupAddress('0:0:0:0:0:ffff:1.2.3.4'));
console.log(cleanupAddress('::1'));
console.log(cleanupAddress('2001:0db8:85a3:0000:0000:8a2e:0370:7334'));

输出:

1.2.3.4
1.2.3.4
1.2.3.4
1.2.3.4
::1
2001:0db8:85a3:0000:0000:8a2e:0370:7334

这就是我想要的。我并不特别介意添加另一个依赖项,所以这似乎没问题。

假设模块正确实现,这应该为任何形式的IPv4和IPv6兼容地址提供完全支持。

对于好奇的人来说,这是一个更完整的测试:

var ip = require('ipaddr.js')

function test (str) {
    console.log(str);
    console.log('  IPv4.isValid:', ip.IPv4.isValid(str));
    console.log('  IPv6.isValid:', ip.IPv6.isValid(str));
    if (ip.IPv6.isValid(str)) {
        var addr = ip.IPv6.parse(str);
        console.log('  IPv6.parse.toString:', addr.toString());
        console.log('  IPv6.isIPv4MappedAddress:', addr.isIPv4MappedAddress());
        if (addr.isIPv4MappedAddress()) {
            console.log('  IPv6.toIPv4Address.toString:', addr.toIPv4Address().toString());
        }
    }
}

test('1.2.3.4')
test('::ffff:1.2.3.4')
test('0:0:0:0:0:ffff:1.2.3.4')
test('::1')
test('2001:0db8:85a3:0000:0000:8a2e:0370:7334')

哪个输出:

1.2.3.4
  IPv4.isValid: true
  IPv6.isValid: false
::ffff:1.2.3.4
  IPv4.isValid: false
  IPv6.isValid: true
  IPv6.parse.toString: ::ffff:102:304
  IPv6.isIPv4MappedAddress: true
  IPv6.toIPv4Address.toString: 1.2.3.4
0:0:0:0:0:ffff:1.2.3.4
  IPv4.isValid: false
  IPv6.isValid: true
  IPv6.parse.toString: ::ffff:102:304
  IPv6.isIPv4MappedAddress: true
  IPv6.toIPv4Address.toString: 1.2.3.4
::1
  IPv4.isValid: false
  IPv6.isValid: true
  IPv6.parse.toString: ::1
  IPv6.isIPv4MappedAddress: false
2001:0db8:85a3:0000:0000:8a2e:0370:7334
  IPv4.isValid: false
  IPv6.isValid: true
  IPv6.parse.toString: 2001:db8:85a3::8a2e:370:7334
  IPv6.isIPv4MappedAddress: false