Skip to content

Use a Library for Public/Private IP Namespaces

How can you tell if a given IP address is within the public or private IP address?

For example, 127.0.0.1 is a known local loopback address. What about https://172.32.1.2 ? Is it public or private?

Leverage an IP Address Library

import ipaddress from 'ipaddr.js'
const ip = userIp // get the user's IP address, e.g: 172.32.1.2
const ipObj = ipaddress.parse(ip)
if (ip instanceof ipaddress.IPv6 && ip.isIPv4MappedAddress()) {
ip = ip.toIPv4Address()
}
if (ip.range() !== 'unicast') {
return true
}