Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns

Node.js net.isIP() method

Reference for net.isIP(), net.isIPv4() and net.isIPv6() in Node.js: check whether a string is a valid IP address, with edge cases for ports, zones and CIDR.

net.isIP(input) tells you whether a string is an IP address and which version it is. It returns 4 for an IPv4 address, 6 for an IPv6 address, and 0 when the input is neither. Two shortcuts exist: net.isIPv4() and net.isIPv6() return booleans.

The check is purely syntactic and runs locally: it does not resolve names, does not look at the network, and does not tell you whether the address is reachable or private. A host name such as example.com simply returns 0.

NODE
import net from 'node:net';

net.isIP('192.168.0.1'); // 4
net.isIP('::1');         // 6
net.isIP('localhost');   // 0

Try it

Node.js Classifying inputs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Choosing between a literal and a lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
net.isIP(input: string): 0 | 4 | 6
net.isIPv4(input: string): boolean
net.isIPv6(input: string): boolean
Name Description
input The text to test. Non-strings are converted to a string first, so numbers and null just return 0.

Returns: 4, 6 or 0. The helper forms return true or false.

Edge cases: a port suffix (1.2.3.4:80), a CIDR suffix (/24) and surrounding brackets ([::1]) make the input invalid. An IPv6 zone identifier (fe80::1%eth0) is accepted. Four-part IPv4 only: shorthand like 127.1 is not an address here.

Usage notes

  • Zero is falsy. if (net.isIP(value)) reads naturally as "is an IP", but remember the version number when you need it.
  • Not a security filter on its own. A valid IP can still be loopback, private or link-local. For SSRF protection, check the resolved address against ranges, for example with net.BlockList.
  • Leading zeros. Node rejects 01.2.3.4 as ambiguous (it could be octal) rather than guessing.
  • Mapped addresses. ::ffff:1.2.3.4 is IPv6 syntax and returns 6, even though it represents an IPv4 host.
  • Use URL for host and port. To split host:port or [::1]:80, parse with new URL('tcp://' + text) first, then test the hostname (strip the brackets for IPv6).
  • Fast. It is a short pure check, safe to call on every request.