Pyderman
Pyderman

Reputation: 16199

Regex: How to match IP address in RFC1918 private IPV4 address ranges (in Python)?

RFC1918 defines private IPv4 addresses as those that fall within any of the following ranges:

10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255

I'm adding 127.0.0.1 to this list, for the purposes of my analysis. I know there are tried-and tested regex's to match any IPv4 address, but how would I narrow one of these to down to matching only if the address falls in one of the above ranges or in 127.0.0.1? Will be using Python.

Many thanks

Upvotes: 3

Views: 8320

Answers (3)

thatjoe
thatjoe

Reputation: 1

(?:(?:192\.)(?:(?:168\.)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(?:(?:10\.)(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){2}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(?:(?:172\.)(?:(?:1[6-9]|2[0-9]|3[0-1])\.)(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))

This regex works for fetching all private ips from a string. Demo can be found here

Upvotes: 0

Jonas Schäfer
Jonas Schäfer

Reputation: 20718

In Python 3.3+ (you did not specify a version, nor why regular expressions are a requirement, so I’ll put this here for completeness), you can:

import ipaddress

addr_string = # string with your IP address
try:
    addr = ipaddress.IPv4Address(addr_string)
except ValueError:
    raise # not an IP address
if addr.is_private:
    pass # is a private address

See also: ipaddress module documentation

Upvotes: 7

Barmar
Barmar

Reputation: 780984

The following regexp should work:

^(?:10|127|172\.(?:1[6-9]|2[0-9]|3[01])|192\.168)\..*

DEMO

Upvotes: 4

Related Questions