I’m trying to find an IP address that match a range of hosts (172.24.12.???), but none of the following queries are working:
select * from pg_catalog.pg_stat_activity
--where client_addr <> E'(?|172.24.12.)'::inet;
--where client_addr <> E'(://|^)172\.24\.12\.[0-9]'::inet
I’m getting two different errors.
SQL Error [22P02]: ERROR: invalid input syntax for type inet: "(?|172.24.12.)" and
SQL Error [22P02]: ERROR: invalid input syntax for type inet: "(^)172.24.12.[0-9]"
What Am I doing wrong here. Thanks!
2
Answers
PostgreSQL has native utilities to handle IP addresses, you don’t need to use string manipulation as workaround:
Demo code:
To answer this, I did the following (all of the code below is available on the fiddle here):
and
Now, you appear to have your IP addresses as strings. This is not the best idea – it’s always best to use the appropriate data type (operators, comparisons, sorting, indexing, correct values enforced automatically), but in this case, we’ll just have to use strings.
As pointed out by
@ÁlvaroGonzález
, this works nicely with IP addresses:Result:
We’ll just have to use the PostgreSQL cast operator (
::
) to convert these to strings as follows:Result:
The regex above isn’t the best – you could spend all day searching for regexes – for example this:
will also work and is more thorough. It’s up to you to choose which regex covers your needs.