Skip to content

Commit

Permalink
feat: add ip validations to ip addr formats (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
zcstarr authored and daviddias committed Apr 3, 2018
1 parent b097af9 commit 70c138b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"bs58": "^4.0.1",
"class-is": "^0.5.0",
"ip": "^1.1.5",
"ip-address": "^5.8.9",
"lodash.filter": "^4.6.0",
"lodash.map": "^4.6.0",
"varint": "^5.0.0",
Expand Down
9 changes: 8 additions & 1 deletion src/convert.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const ip = require('ip')
const ipAddress = require('ip-address')
const protocols = require('./protocols-table')
const bs58 = require('bs58')
const varint = require('varint')
Expand Down Expand Up @@ -45,8 +46,9 @@ Convert.toBuffer = function convertToBuffer (proto, str) {
proto = protocols(proto)
switch (proto.code) {
case 4: // ipv4
return ip2buf(new ipAddress.Address4(str))
case 41: // ipv6
return ip.toBuffer(str)
return ip2buf(new ipAddress.Address6(str))

case 6: // tcp
case 17: // udp
Expand All @@ -66,6 +68,11 @@ Convert.toBuffer = function convertToBuffer (proto, str) {
}
}

function ip2buf (ipaddr) {
if (!ipaddr.isValid()) throw new Error('invalid ip address')
return ip.toBuffer(ipaddr.address)
}

function port2buf (port) {
const buf = Buffer.alloc(2)
buf.writeUInt16BE(port, 0)
Expand Down
36 changes: 34 additions & 2 deletions test/convert.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,54 @@ const expect = chai.expect
chai.use(dirtyChai)

describe('convert', () => {
it('handles buffers', () => {
it('handles ip4 buffers', () => {
expect(
convert('ip4', Buffer.from('c0a80001', 'hex'))
).to.eql(
'192.168.0.1'
)
})

it('handles strings', () => {
it('handles ip6 buffers', () => {
expect(
convert('ip6', Buffer.from('abcd0000000100020003000400050006', 'hex'))
).to.eql(
'abcd:0:1:2:3:4:5:6'
)
})

it('handles ipv6 strings', () => {
expect(
convert('ip6', 'ABCD::1:2:3:4:5:6')
).to.eql(
Buffer.from('ABCD0000000100020003000400050006', 'hex')
)
})

it('handles ip4 strings', () => {
expect(
convert('ip4', '192.168.0.1')
).to.eql(
Buffer.from('c0a80001', 'hex')
)
})

it('throws on invalid ip4 conversion', () => {
expect(
() => convert('ip4', '555.168.0.1')
).to.throw(
/invalid ip address/
)
})

it('throws on invalid ip6 conversion', () => {
expect(
() => convert('ip6', 'FFFF::GGGG')
).to.throw(
/invalid ip address/
)
})

describe('.toBuffer', () => {
it('defaults to hex conversion', () => {
expect(
Expand Down

0 comments on commit 70c138b

Please sign in to comment.