Skip to content

Commit 9924afa

Browse files
authored
fix: trim string before parsing IP address (#269)
Remove leading and training spaces, also adds tests.
1 parent d6b7f69 commit 9924afa

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

Diff for: src/convert.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ const anybaseDecoder = (function () {
103103

104104
function ip2bytes (ipString: string) {
105105
if (!ip.isIP(ipString)) {
106-
throw new Error('invalid ip address')
106+
throw new Error(`invalid ip address "${ipString}"`)
107107
}
108108
return ip.toBytes(ipString)
109109
}

Diff for: src/ip.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export const isV6 = isIPv6
1010
export const toBytes = function (ip: string): Uint8Array {
1111
let offset = 0
1212
let result
13+
ip = ip.trim()
1314

1415
if (isV4(ip)) {
1516
result = new Uint8Array(offset + 4)
@@ -56,14 +57,14 @@ export const toBytes = function (ip: string): Uint8Array {
5657
}
5758

5859
if (result == null) {
59-
throw Error('Invalid ip address: ' + ip)
60+
throw new Error(`invalid ip address "${ip}"`)
6061
}
6162

6263
return result
6364
}
6465

6566
// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63
66-
export const toString = function (buf: Uint8Array, offset: number, length: number) {
67+
export const toString = function (buf: Uint8Array, offset: number = 0, length?: number) {
6768
offset = ~~offset
6869
length = length ?? (buf.length - offset)
6970

Diff for: test/ip.spec.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/* eslint max-nested-callbacks: ["error", 8] */
2+
/* eslint-env mocha */
3+
import { expect } from 'aegir/chai'
4+
import { toBytes, toString } from '../src/ip.js'
5+
6+
describe('ip', () => {
7+
describe('toBytes', () => {
8+
it('should handle extra characters', () => {
9+
const address = '127.0.0.1 '
10+
const bytes = toBytes(address)
11+
12+
expect(toString(bytes)).to.equal(address.trim())
13+
})
14+
15+
it('should turn loopback into bytes', () => {
16+
const address = '127.0.0.1'
17+
const bytes = toBytes(address)
18+
19+
expect(toString(bytes)).to.equal(address)
20+
})
21+
22+
it('should turn private address into bytes', () => {
23+
const address = '192.168.1.1'
24+
const bytes = toBytes(address)
25+
26+
expect(toString(bytes)).to.equal(address)
27+
})
28+
})
29+
})

0 commit comments

Comments
 (0)