Represent address as integer
Encode or decode an ip_address
as an integer.
Note: The result is a character vector (see below for why). This can be
converted using as.numeric()
for IPv4 addresses.
ip_to_integer(x, base = c("dec", "hex", "bin")) integer_to_ip(x, is_ipv6 = NULL)
x |
|
base |
A string choosing the numeric base of the output. Choices are
decimal ( |
is_ipv6 |
A logical vector indicating whether to construct an IPv4 or
IPv6 address. If |
It is common to represent an IP address as an integer, by reinterpreting
the bit sequence as a big-endian unsigned integer. This means IPv4 and IPv6
addresses can be represented by 32-bit and 128-bit unsigned integers.
In this way, the IPv4 addresses 0.0.0.0
and 255.255.255.255
would be
represented as 0 and 4,294,967,295.
For ip_to_integer()
: A character vector
For integer_to_ip()
: An ip_address
vector
For the purpose of storing IP addresses as integers, we need to be able to
store a large range of positive integers without losing integer precision.
Under these circumstances, the integer
type can store integers up to
2^31 - 1 and the double
type can store integers up to 2^53. However,
for IPv4 and IPv6 addresses we need to store integers up to 2^32 - 1 and
2^128 - 1, respectively. This means an IPv4 address can be stored in a
double
, but an IPv6 address cannot be stored in either R data type.
Although the integer representation of an IPv6 address cannot be stored in
a numeric R data type, it can be stored as a character string instead.
This allows the integer to be written to disk or used by other software that
does support 128-bit unsigned integers. To treat IPv4 and IPv6 equally,
ip_to_integer()
will always return a character
vector. With IPv4
addresses, this output can be converted to a double
vector using
as.double()
or as.numeric()
. With IPv6 addresses, this conversion loses
the distinction between individual addresses because integer precision is lost.
x <- ip_address(c("192.168.0.1", "2001:db8::8a2e:370:7334", NA)) ip_to_integer(x) integer_to_ip(ip_to_integer(x)) # with IPv4 only, we can use numeric data type as.numeric(ip_to_integer(ip_address("192.168.0.1"))) integer_to_ip(3232235521) # hex representation ip_to_integer(x, base = "hex")
Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.