Postgresql has the inet and cidr datatypes and some great functions for these types, very useful for storing and manipulating data for IP addresses and networks. Here is how to query for the next sequentially available IP address in a given table.
As a basic example, say you were storing hostnames and IP addresses as below:
CREATE TABLE ip_table (
id serial NOT NULL,
ip_address inet NOT NULL,
hostname character varying(25) NOT NULL
);
| id | ip_address | hostname |
| 1 | 10.10.100.15 | server01 |
If I wanted to add a new host then I would want to give it a unique IP address so I would have to find the next available IP address (defined as NOT already in this table) in order to allocate. Below is a query that generates a series of inets for the network passed and then looks to see if they are already in the table. An optional extra on the end is not selecting the first 10 or the last 5 IP address of a subnet – if you want to reserve these.
Just substitue the subnet and ip_table tablename;
Here is the create function script to create a function to call for the above query.
Again, just substitue the ip_table tablename for what you’re using;