Reputation: 17637
Is it necessary to use an unsigned integer column to store an IP(v4) address (that has been converted with INET_ATON
) in MySQL?
I spontaneous would think that it really does NOT matter, since no matter how the field is defined, the same data will be used to convert it back with INET_NTOA
.
So the only difference would be, that in one case you see a negative number in your db while with unsigned you would see a (totally) different positive number, while the actual data is the same in both cases, just representation differs through field definition, is that correct?
Upvotes: 1
Views: 1352
Reputation: 17637
Short answer: USIGNED
is necessary, if you want to store an IP with it's first octet greater than 127!
From the MySQL Docs about 11.2.6 Out-of-Range and Overflow Handling:
If strict SQL mode is enabled, MySQL rejects the out-of-range value with an error, and the insert fails, in accordance with the SQL standard.
If no restrictive modes are enabled, MySQL clips the value to the appropriate endpoint of the range and stores the resulting value instead.
So what happens if you try to store an IP address greater than 127.255.255.255 in a SIGNED INTEGER
field, depends on wether restrictive modes are enabled or not, but in either case it does NOT work as you would want it to.
When an out-of-range value is assigned to an integer column, MySQL stores the value representing the corresponding endpoint of the column data type range. If you store 256 into a
TINYINT
orTINYINT UNSIGNED
column, MySQL stores 127 or 255, respectively.
Upvotes: 1
Reputation: 35337
From the docs on INET_ATON():
To store values generated by INET_ATON(), use an INT UNSIGNED column rather than INT, which is signed. If you use a signed column, values corresponding to IP addresses for which the first octet is greater than 127 cannot be stored correctly. See Section 11.2.6, “Out-of-Range and Overflow Handling.
Why not just use an unsigned to guarantee compatibility? What are the downsides to using unsigned in your scenario that would make you question this?
Upvotes: 5