@chainsafe/is-ip
Check if a string is an IP address
Install
npm install @chainsafe/is-ip
Example
import { expect } from "chai";
import {
parseIPv4,
parseIPv6,
parseIP,
} from "@chainsafe/is-ip";
const b1 = parseIPv4("127.0.0.1");
expect(b1).to.deep.equal(Uint8Array.from([127, 0, 0, 1]));
const b2 = parseIPv6("::1");
expect(b2).to.deep.equal(Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]));
const b3 = parseIP("127.0.0.1");
expect(b3).to.deep.equal(Uint8Array.from([127, 0, 0, 1]));
const b4 = parseIP("::1");
expect(b4).to.deep.equal(Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]));
try {
parseIP("not an IP");
expect.fail("not reached");
} catch (e) {}
import {
isIPv4,
isIPv6,
isIP,
ipVersion,
} from "@chainsafe/is-ip";
expect(isIPv4("127.0.0.1")).to.equal(true);
expect(isIPv6("127.0.0.1")).to.equal(false);
expect(isIP("127.0.0.1")).to.equal(true);
expect(ipVersion("127.0.0.1")).to.equal(4);
expect(ipVersion("1:2:3:4:5:6:7:8")).to.equal(6);
expect(ipVersion("invalid ip")).to.equal(undefined);
License
MIT