简体   繁体   中英

Storing IP with INET_ATON - signed or unsigned integer?

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?

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?

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.

Even if no restrictive modes are enabled ...

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 or TINYINT UNSIGNED column, MySQL stores 127 or 255, respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM