what should be the ideal size for storing IPv4, IPv6 addresses as a string in the MySQL database. should varchar(32) be sufficient?
Numerically, an IPv4 address is 32-bit long and IPv6 address is 128-bit long. So you need a storage of at least 16 bytes.
If the "string" you store is an encoding of the address in byte form, then 16 is enough.
If you're storing them as strings rather than bit patterns:
IPv4 addresses consist of four 3-digit decimal characters with three .
separators, so that only takes 15 characters such as 255.255.255.255
.
IPv6 addresses consist of eight 4-digit hex characters with seven :
separators, so that takes 39 characters such as 0123:4567:89ab:cdef:0123:4567:89ab:cdef
.
Assuming textual representation in a string :
- 15 characters for IPv4 (
xxx.xxx.xxx.xxx
format, 12+3 separators) - 39 characters (32 + 7 separators) for IPv6
Those are the maximum length of the string.
Alternatives to storing as string:
- IPv4 is 32-bits, so a MySQL data type that can hold 4 bytes will do, using
INT UNSIGNED
is common along withINT_ATON
andINET_NTOA
to handle the conversion from address to number, and from number to address
SELECT INET_ATON('209.207.224.40'); -> 3520061480 SELECT INET_NTOA(3520061480); -> '209.207.224.40'
- For IPv6, unfortunately MySQL does not have a data type that is 16 bytes, however one can put the IPv6 into a canonical form, then separate them into 2
BIGINT
(8 bytes), this however will use two fields.
Assuming you don't have any network information (such as LL identifier, class, or CIDR mask) attached, an IPv4 address is up to fifteen characters (4x3 numbers+3 periods) and an IPv6 address may be up to 39 characters.
- do not store IP address as a string
- do not mix ipv6 addresses with ipv4 ones
- ipv6 is a matter of distant future
- ipv4 address length is 4 bytes, thus, common INT unsigned is enough and the only possible option for the ipv4.
- if you really plan to use ipv6, 2 bigint unsigned fields is the option.