DEV Community

Cover image for IP Address Regex Is a Trap: Validate IPs Properly in JavaScript, Python and Go
IPLogs
IPLogs

Posted on

IP Address Regex Is a Trap: Validate IPs Properly in JavaScript, Python and Go

Search for "ip address regex," and you will find patterns that look clever and fail quietly. Some accept 999.999.999.999. Others reject perfectly valid IPv6 addresses. A few let a trailing newline slip into your database.

The fix is boring and reliable: every mainstream language ships an IP parser. This post shows where regex breaks, then the three lines of code to use instead in JavaScript, Python and Go.

The regex everyone copies

Here is the classic first attempt, next to the "strict" version people upgrade to:

const naive = /^\d{1,3}(\.\d{1,3}){3}$/;
const strict = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;

for (const s of ["192.168.1.1", "999.999.999.999", "010.0.0.1", "1.2.3.4\n"]) {
  console.log(JSON.stringify(s).padEnd(20), "naive:", naive.test(s), " strict:", strict.test(s));
}
Enter fullscreen mode Exit fullscreen mode

Output:

"192.168.1.1"        naive: true  strict: true
"999.999.999.999"    naive: true  strict: false
"010.0.0.1"          naive: true  strict: false
"1.2.3.4\n"          naive: false  strict: false
Enter fullscreen mode Exit fullscreen mode

The strict pattern handles IPv4 well. So why not stop there? Because IPv4 is the easy half.

Where regex falls apart

IPv6 has too many legal spellings. 2001:db8::1, 2001:0db8:0000:0000:0000:0000:0000:0001 and 2001:DB8::1 are the same address. The :: shortcut may appear once, never twice. Addresses can embed IPv4 (::ffff:192.0.2.1) and link local addresses can carry a zone (fe80::1%eth0). A regex that covers all of that is hundreds of characters long, and nobody on your team will review it properly.

Leading zeros are ambiguous. Some older parsers read 010 as octal, which is 8. Python's documentation is blunt about it: leading zeros "are not tolerated to prevent confusion with octal notation", and since Python 3.9.5 they are an error.

You can see the octal problem today in the URL parser your browser and Node share:

for (const host of ["0x7f.1", "2130706433", "0177.0.0.1", "127.1"]) {
  console.log(host.padEnd(12), "->", new URL(`http://${host}/`).hostname);
}
Enter fullscreen mode Exit fullscreen mode
0x7f.1       -> 127.0.0.1
2130706433   -> 127.0.0.1
0177.0.0.1   -> 127.0.0.1
127.1        -> 127.0.0.1
Enter fullscreen mode Exit fullscreen mode

All four strings point at localhost. If your app checks a hostname with a regex but later fetches it with a URL library, those two parts disagree. That gap is exactly how server side request forgery filters get bypassed. (More on that later in this series.)

Python's $ has a surprise. In Python, $ also matches right before a final newline:

import re

octet = r"(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)"
pattern = re.compile(rf"^{octet}(\.{octet}){{3}}$")

print(bool(pattern.match("1.2.3.4\n")))      # True: $ also matches before a final newline
print(bool(pattern.fullmatch("1.2.3.4\n")))  # False
Enter fullscreen mode Exit fullscreen mode

So "1.2.3.4\n" passes validation and lands in your database with the newline attached.

Use the parser your language already has

JavaScript (Node.js)

const net = require("node:net");

const inputs = ["192.168.1.1", "999.1.1.1", "010.0.0.1", "1.2.3", "::1",
  "2001:db8::1", "fe80::1%eth0", "::ffff:192.0.2.1", "2001:db8:::1", " 10.0.0.1"];

for (const s of inputs) {
  console.log(JSON.stringify(s).padEnd(20), net.isIP(s)); // 4, 6 or 0
}
Enter fullscreen mode Exit fullscreen mode

net.isIP() returns 4, 6 or 0. In our run it rejected 999.1.1.1, 010.0.0.1, 1.2.3, the triple colon and the leading space, and accepted every valid IPv6 form.

In the browser there is no isIP, but you can let the URL parser normalise an IPv6 literal for you: new URL("http://[2001:DB8:0:0::1]/").hostname returns [2001:db8::1].

Python

import ipaddress

inputs = ["192.168.1.1", "999.1.1.1", "010.0.0.1", "1.2.3", "::1",
          "2001:db8::1", "fe80::1%eth0", "::ffff:192.0.2.1", "2001:db8:::1", " 10.0.0.1"]

for s in inputs:
    try:
        ip = ipaddress.ip_address(s)
        print(f"{s!r:22} IPv{ip.version}  {ip.compressed}")
    except ValueError:
        print(f"{s!r:22} invalid")
Enter fullscreen mode Exit fullscreen mode

ip_address() raises ValueError for anything invalid and gives you a real object for everything else. You also get useful properties for free: .version, .compressed, .is_private, .is_loopback, and .ipv4_mapped for addresses like ::ffff:192.0.2.1.

Go

package main

import (
    "fmt"
    "net/netip"
)

func main() {
    inputs := []string{"192.168.1.1", "999.1.1.1", "010.0.0.1", "1.2.3", "::1",
        "2001:db8::1", "fe80::1%eth0", "::ffff:192.0.2.1", "2001:db8:::1", " 10.0.0.1"}

    for _, s := range inputs {
        addr, err := netip.ParseAddr(s)
        if err != nil {
            fmt.Printf("%-22q invalid\n", s)
            continue
        }
        kind := "IPv6"
        if addr.Is4() {
            kind = "IPv4"
        }
        fmt.Printf("%-22q %s  %s  mapped=%v\n", s, kind, addr, addr.Is4In6())
    }
}
Enter fullscreen mode Exit fullscreen mode

netip.Addr is a small comparable value type, so you can use it as a map key, and Is4In6() tells you when an IPv6 address is really wrapping an IPv4 one.

The results side by side

All three parsers agreed on every input in our test run:

Input Node isIP Python ip_address Go ParseAddr
192.168.1.1 4 IPv4 IPv4
999.1.1.1 0 invalid invalid
010.0.0.1 0 invalid invalid
1.2.3 0 invalid invalid
::1 6 IPv6 IPv6
fe80::1%eth0 6 IPv6 IPv6
::ffff:192.0.2.1 6 IPv6 IPv6 (mapped)
2001:db8:::1 0 invalid invalid
" 10.0.0.1" 0 invalid invalid

When regex is fine: finding, not validating

Regex still has a job: pulling candidates out of logs or free text. Just let the parser make the final call.

import ipaddress
import re

log = """
10.0.0.5 - - "GET / HTTP/1.1" 200
999.1.2.3 - - "GET /admin HTTP/1.1" 404
build 1.2.3.4567 finished
2001:db8::42 - - "POST /login HTTP/1.1" 401
"""

# Step 1: a loose pattern finds candidates. Step 2: the parser decides.
candidates = re.findall(r"[0-9A-Fa-f:.]{3,}", log)
valid = []
for c in candidates:
    try:
        valid.append(str(ipaddress.ip_address(c.strip(".:"))))
    except ValueError:
        pass
print(valid)  # ['10.0.0.5', '2001:db8::42']
Enter fullscreen mode Exit fullscreen mode

The loose pattern happily matches 999.1.2.3, 1.2.3.4567 and 1.1 from HTTP/1.1. The parser throws them all out.

A short checklist

  • Validate with net.isIP, ipaddress.ip_address or netip.ParseAddr, never a hand written regex.
  • Store the parser's normalised form (for IPv6, the compressed lowercase form) so the same address always looks the same.
  • Decide up front whether you accept zone IDs like %eth0. Most web apps should strip or reject them.
  • Watch for IPv4 mapped IPv6 addresses. A server can report ::ffff:203.0.113.7 for an IPv4 client.
  • Never validate with one parser and connect with another.

Wrapping up

Regex is great at finding text that looks like an IP address and bad at deciding whether it is one. Use the parser your language ships with and the edge cases disappear.

Next in the series: why the X-Forwarded-For header lies, and how to read the real client IP safely. Have you ever been bitten by an IP validation bug? I would love to hear the story in the comments.

This post was drafted with AI assistance and reviewed by the author before publishing.

Further reading

Top comments (0)