-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0ccf5a2
commit cfdec37
Showing
3 changed files
with
52 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { stripPort } from './ip' | ||
|
||
describe('Strip port', () => { | ||
it('strip port from ipv4 address', () => { | ||
expect(stripPort('237.84.2.178:80')).toBe('237.84.2.178') | ||
}) | ||
|
||
it('ipv6 without port', () => { | ||
expect(stripPort('5be8:dde9:7f0b:d5a7:bd01:b3be:9c69:573b')).toBe('5be8:dde9:7f0b:d5a7:bd01:b3be:9c69:573b') | ||
}) | ||
|
||
it('ipv4 without port', () => { | ||
expect(stripPort('237.84.2.178')).toBe('237.84.2.178') | ||
}) | ||
|
||
it('strip port from ipv6 address', () => { | ||
expect(stripPort('[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:443')).toBe('2001:0db8:85a3:0000:0000:8a2e:0370:7334') | ||
}) | ||
|
||
it.each(['127.0', 'invalid', 'localhost', '2001:0db8:85a3:0000:0000'])('invalid ip: %s', (data) => { | ||
expect(stripPort(data)).toBe(data) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { isIPv4, isIPv6 } from 'net' | ||
|
||
export function stripPort(ip: string) { | ||
// Check if it's an IPv6 address with a port | ||
if (ip.startsWith('[')) { | ||
// IPv6 address with port | ||
const closingBracketIndex = ip.indexOf(']') | ||
if (closingBracketIndex !== -1) { | ||
return ip.substring(1, closingBracketIndex) | ||
} | ||
} else { | ||
// IPv4 address with port or IPv6 without brackets | ||
const colonIndex = ip.lastIndexOf(':') | ||
if (colonIndex !== -1) { | ||
const ipWithoutPort = ip.substring(0, colonIndex) | ||
// Validate if the part before the colon is a valid IPv4 or IPv6 address | ||
if (isValidIp(ipWithoutPort)) { | ||
return ipWithoutPort | ||
} | ||
} | ||
} | ||
// If no port is found, return the original IP | ||
return ip | ||
} | ||
|
||
function isValidIp(ip: string) { | ||
return isIPv4(ip) || isIPv6(ip) | ||
} |