| Документация по PostgreSQL 9.4.1 | |||
|---|---|---|---|
| Пред. | Уровень выше | Глава 9. Функции и операторы | След. |
9.12. Функции и операторы для работы с сетевыми адресами
В Таблица 9-34 показаны операторы, работающие с типами cidr и inet. Операторы <<, <<=, >>, >>= и && проверяют включения подсетей, рассматривая только биты сети в обоих адресах (игнорируя биты узлов) и определяя, идентична ли одна сеть другой или её подсети.
Таблица 9-34. Операторы для типов cidr и inet
| Оператор | Описание | Пример |
|---|---|---|
| < | меньше | inet '192.168.1.5' < inet '192.168.1.6' |
| <= | меньше или равно | inet '192.168.1.5' <= inet '192.168.1.5' |
| = | равно | inet '192.168.1.5' = inet '192.168.1.5' |
| >= | больше или равно | inet '192.168.1.5' >= inet '192.168.1.5' |
| > | больше | inet '192.168.1.5' > inet '192.168.1.4' |
| <> | не равно | inet '192.168.1.5' <> inet '192.168.1.4' |
| << | содержится в | inet '192.168.1.5' << inet '192.168.1/24' |
| <<= | равно или содержится в | inet '192.168.1/24' <<= inet '192.168.1/24' |
| >> | содержит | inet '192.168.1/24' >> inet '192.168.1.5' |
| >>= | равно или содержит | inet '192.168.1/24' >>= inet '192.168.1/24' |
| && | содержит или содержится в | inet '192.168.1/24' && inet '192.168.1.80/28' |
| ~ | битовый NOT | ~ inet '192.168.1.6' |
| & | битовый AND | inet '192.168.1.6' & inet '0.0.0.255' |
| | | битовый OR | inet '192.168.1.6' | inet '0.0.0.255' |
| + | сложение | inet '192.168.1.6' + 25 |
| - | вычитание | inet '192.168.1.43' - 36 |
| - | вычитание | inet '192.168.1.43' - inet '192.168.1.19' |
В Таблице 9-35 перечислены функции, работающие с типами cidr и inet. Функции abbrev, host и text предназначены в основном для вывода данных в альтернативных форматах.
Таблица 9-35. Функции для типов cidr и inet
| Функция | Тип результата | Описание | Пример | Результат |
|---|---|---|---|---|
abbrev(inet) | text | вывод адрес в кратком текстовом виде | abbrev(inet '10.1.0.0/16') | 10.1.0.0/16 |
abbrev(cidr) | text | вывод адрес в кратком текстовом виде | abbrev(cidr '10.1.0.0/16') | 10.1/16 |
broadcast(inet) | inet | широковещательный адрес сети | broadcast('192.168.1.5/24') | 192.168.1.255/24 |
family(inet) | int | возвращает семейство адреса; 4 для адреса IPv4, 6 для IPv6 | family('::1') | 6 |
host(inet) | text | извлекает IP-адрес в виде текста | host('192.168.1.5/24') | 192.168.1.5 |
hostmask(inet) | inet | вычисляет маску узла для сетевого адреса | hostmask('192.168.23.20/30') | 0.0.0.3 |
masklen(inet) | int | выдаёт длину маски сети | masklen('192.168.1.5/24') | 24 |
netmask(inet) | inet | вычисляет маску сети для сетевого адреса | netmask('192.168.1.5/24') | 255.255.255.0 |
network(inet) | cidr | извлекает компонент сети из адреса | network('192.168.1.5/24') | 192.168.1.0/24 |
set_masklen(inet, int) | inet | задаёт размер маски для значения inet | set_masklen('192.168.1.5/24', 16) | 192.168.1.5/16 |
set_masklen(cidr, int) | cidr | задаёт размер маски для значения cidr | set_masklen('192.168.1.0/24'::cidr, 16) | 192.168.0.0/16 |
text(inet) | text | выводит в текстовом виде IP-адрес и длину маски | text(inet '192.168.1.5') | 192.168.1.5/32 |
Любое значение cidr можно привести к типу inet, явно или нет; поэтому все функции, показанные выше с типом inet, также будут работать со значениями cidr. (Некоторые из функций указаны отдельно для типов inet и cidr, потому что их поведение с разными типами различается.) Кроме того, значение inet тоже можно привести к типу cidr. При этом все биты справа от сетевой маски просто обнуляются, чтобы значение стало допустимым для типа cidr. К типам inet и cidr можно привести и обычные текстовые значения, используя обычный синтаксис, например: inet(выражение) или колонка::cidr.
В Таблице 9-36 приведена функция, предназначенная для работы с типом macaddr. Функция trunc(macaddr) возвращает MAC-адрес, последние 3 байта в котором равны 0. Это может быть полезно для вычисления префикса, определяющего производителя.
Таблица 9-36. Функции macaddr
| Функция | Тип результата | Описание | Пример | Результат |
|---|---|---|---|---|
trunc(macaddr) | macaddr | обнуляет последние 3 байта | trunc(macaddr '12:34:56:78:90:ab') | 12:34:56:00:00:00 |
Тип macaddr также поддерживает стандартные реляционные операторы лексической сортировки (>, <= и т. д.) и операторы битовой арифметики (~, & и |), соответствующие операциям NOT, AND и OR.
| Пред. | Начало | След. |
| Геометрические функции и операторы | Уровень выше | Функции и операторы текстового поиска |
| PostgreSQL 9.4.1 Documentation | |||
|---|---|---|---|
| Prev | Up | Chapter 9. Functions and Operators | Next |
9.12. Network Address Functions and Operators
Table 9-34 shows the operators available for the cidr and inet types. The operators <<, <<=, >>, >>=, and && test for subnet inclusion. They consider only the network parts of the two addresses (ignoring any host part) and determine whether one network is identical to or a subnet of the other.
Table 9-34. cidr and inet Operators
| Operator | Description | Example |
|---|---|---|
| < | is less than | inet '192.168.1.5' < inet '192.168.1.6' |
| <= | is less than or equal | inet '192.168.1.5' <= inet '192.168.1.5' |
| = | equals | inet '192.168.1.5' = inet '192.168.1.5' |
| >= | is greater or equal | inet '192.168.1.5' >= inet '192.168.1.5' |
| > | is greater than | inet '192.168.1.5' > inet '192.168.1.4' |
| <> | is not equal | inet '192.168.1.5' <> inet '192.168.1.4' |
| << | is contained by | inet '192.168.1.5' << inet '192.168.1/24' |
| <<= | is contained by or equals | inet '192.168.1/24' <<= inet '192.168.1/24' |
| >> | contains | inet '192.168.1/24' >> inet '192.168.1.5' |
| >>= | contains or equals | inet '192.168.1/24' >>= inet '192.168.1/24' |
| && | contains or is contained by | inet '192.168.1/24' && inet '192.168.1.80/28' |
| ~ | bitwise NOT | ~ inet '192.168.1.6' |
| & | bitwise AND | inet '192.168.1.6' & inet '0.0.0.255' |
| | | bitwise OR | inet '192.168.1.6' | inet '0.0.0.255' |
| + | addition | inet '192.168.1.6' + 25 |
| - | subtraction | inet '192.168.1.43' - 36 |
| - | subtraction | inet '192.168.1.43' - inet '192.168.1.19' |
Table 9-35 shows the functions available for use with the cidr and inet types. The abbrev, host, and text functions are primarily intended to offer alternative display formats.
Table 9-35. cidr and inet Functions
| Function | Return Type | Description | Example | Result |
|---|---|---|---|---|
abbrev(inet) | text | abbreviated display format as text | abbrev(inet '10.1.0.0/16') | 10.1.0.0/16 |
abbrev(cidr) | text | abbreviated display format as text | abbrev(cidr '10.1.0.0/16') | 10.1/16 |
broadcast(inet) | inet | broadcast address for network | broadcast('192.168.1.5/24') | 192.168.1.255/24 |
family(inet) | int | extract family of address; 4 for IPv4, 6 for IPv6 | family('::1') | 6 |
host(inet) | text | extract IP address as text | host('192.168.1.5/24') | 192.168.1.5 |
hostmask(inet) | inet | construct host mask for network | hostmask('192.168.23.20/30') | 0.0.0.3 |
masklen(inet) | int | extract netmask length | masklen('192.168.1.5/24') | 24 |
netmask(inet) | inet | construct netmask for network | netmask('192.168.1.5/24') | 255.255.255.0 |
network(inet) | cidr | extract network part of address | network('192.168.1.5/24') | 192.168.1.0/24 |
set_masklen(inet, int) | inet | set netmask length for inet value | set_masklen('192.168.1.5/24', 16) | 192.168.1.5/16 |
set_masklen(cidr, int) | cidr | set netmask length for cidr value | set_masklen('192.168.1.0/24'::cidr, 16) | 192.168.0.0/16 |
text(inet) | text | extract IP address and netmask length as text | text(inet '192.168.1.5') | 192.168.1.5/32 |
Any cidr value can be cast to inet implicitly or explicitly; therefore, the functions shown above as operating on inet also work on cidr values. (Where there are separate functions for inet and cidr, it is because the behavior should be different for the two cases.) Also, it is permitted to cast an inet value to cidr. When this is done, any bits to the right of the netmask are silently zeroed to create a valid cidr value. In addition, you can cast a text value to inet or cidr using normal casting syntax: for example, inet(expression) or colname::cidr.
Table 9-36 shows the functions available for use with the macaddr type. The function trunc(macaddr) returns a MAC address with the last 3 bytes set to zero. This can be used to associate the remaining prefix with a manufacturer.
Table 9-36. macaddr Functions
| Function | Return Type | Description | Example | Result |
|---|---|---|---|---|
trunc(macaddr) | macaddr | set last 3 bytes to zero | trunc(macaddr '12:34:56:78:90:ab') | 12:34:56:00:00:00 |
The macaddr type also supports the standard relational operators (>, <=, etc.) for lexicographical ordering, and the bitwise arithmetic operators (~, & and |) for NOT, AND and OR.