Test if string is an IP address in Node.js

Revision history
Tags: node.js

I just found some new (since v0.3.0) functions in the Node.js net module. These functions enables you to check if you have a valid IP address regardless of family, or if it is specifically an IPv4 or IPv6 address.

const net = require('net')
const assert = require('assert')

assert.strictEqual(net.isIP('127.0.0.1'), 4);
assert.strictEqual(net.isIP('x127.0.0.1'), 0);
assert.strictEqual(net.isIP('example.com'), 0);
assert.strictEqual(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000'), 6);

assert.strictEqual(net.isIPv4('127.0.0.1'), true);
assert.strictEqual(net.isIPv4('example.com'), false);

assert.strictEqual(net.isIPv6('127.0.0.1'), false);
assert.strictEqual(net.isIPv6('2001:252:0:1::2008:6'), true);

The above tests are taken from the upstream repository.

References

If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom).

Did you find any typos, incorrect information, or have something to add? Then please propose a change to this post.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.