Introduction to PostgreSQL inet Data Type

The PostgreSQL inet data type is used for storing and processing IPv4 or IPv6 addresses. IPv4 addresses are 32-bit addresses typically represented as four decimal numbers separated by dots, such as 192.0.2.123. IPv6 addresses are 128-bit addresses typically represented as eight groups of hexadecimal numbers separated by colons, such as 2001:0db8:85a3:0000:0000:8a2e:0370:7334.

Syntax

In PostgreSQL, the following syntax can be used to create a column with the inet data type:

column_name INET

Use Cases

The inet data type is commonly used in network programming to store IPv4 or IPv6 address information. In an application, the inet data type can be used to store client IP addresses, server IP addresses, router IP addresses, etc.

Examples

Here are two examples of using the inet data type:

Example 1

In this example, we create a table named users with three columns: id, username, and ip_address, where the ip_address column has the data type of inet. We insert two user records into the table, each with a username and an IPv4 address.

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  ip_address INET NOT NULL
);

INSERT INTO users (username, ip_address) VALUES ('Alice', '192.0.2.123');
INSERT INTO users (username, ip_address) VALUES ('Bob', '192.0.2.234');

Example 2

In this example, we create a table named servers with three columns: id, name, and ip_address, where the ip_address column has the data type of inet. We insert two server records into the table, each with a name and an IPv6 address.

CREATE TABLE servers (
  id SERIAL PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  ip_address INET NOT NULL
);

INSERT INTO servers (name, ip_address) VALUES ('Server1', '2001:0db8:85a3:0000:0000:8a2e:0370:7334');
INSERT INTO servers (name, ip_address) VALUES ('Server2', '2001:0db8:85a3:0000:0000:8a2e:0370:7335');

Conclusion

The PostgreSQL inet data type is a convenient way to store and process IPv4 or IPv6 addresses, and it is well-suited for various use cases in network programming. By using the inet data type, you can easily store and manipulate IP address information, making your application more robust and reliable.