IP Address Regex
Test and validate IP address patterns for IPv4 and IPv6 formats. Ensure valid ranges (0-255) and proper formatting.
IPv4 Patterns
``javascript
// Simple IPv4 (doesn't validate range)
const simpleIPv4 = /^\d{1,3}(?:\.\d{1,3}){3}$/;
// Strict IPv4 (validates 0-255)
const strictIPv4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
// Test
strictIPv4.test('192.168.1.1'); // true
strictIPv4.test('255.255.255.255'); // true
strictIPv4.test('256.1.1.1'); // false (256 > 255)
strictIPv4.test('1.2.3'); // false (missing octet)
`
IPv4 Range Breakdown
| Octet Value | Pattern |
0-9\d
10-99[1-9]\d
100-1991\d{2}
200-2492[0-4]\d
250-25525[0-5]
| Combined | 25[0-5]\|2[0-4]\d\|1\d{2}\|[1-9]?\d |
IPv6 Patterns
`javascript
// Simple IPv6 (8 groups of 4 hex digits)
const simpleIPv6 = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
// IPv6 with zero compression (::)
const ipv6WithCompression = /^(?:(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|::(?:[0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4}|::|(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4})$/i;
// Test
simpleIPv6.test('2001:0db8:85a3:0000:0000:8a2e:0370:7334'); // true
ipv6WithCompression.test('::1'); // true (localhost)
ipv6WithCompression.test('2001:db8::1'); // true (compressed)
`
IP Address Validator
`javascript
function validateIP(ip) {
// IPv4 strict pattern
const ipv4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
// IPv6 full pattern
const ipv6 = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,6}:$|^(?:[0-9a-fA-F]{1,4}:){1,5}:[0-9a-fA-F]{1,4}$/i;
if (ipv4.test(ip)) return { valid: true, version: 4 };
if (ipv6.test(ip)) return { valid: true, version: 6 };
return { valid: false, version: null };
}
validateIP('192.168.1.1'); // { valid: true, version: 4 }
validateIP('::1'); // { valid: true, version: 6 }
validateIP('invalid'); // { valid: false, version: null }
``
Special IP Addresses
| Address | Type | Description | 127.0.0.1IPv4Localhost ::1IPv6Localhost 0.0.0.0IPv4All interfaces ::IPv6All interfaces 10.x.x.xIPv4Private (Class A) 172.16-31.x.xIPv4Private (Class B) 192.168.x.xIPv4Private (Class C)