An in depth analysis of inet_aton of and inet_ntoa of processing functions based on Mysql
- 2020-05-17 06:48:01
- OfStack
There is a statistical requirement for classification statistics for IP, which provides processing of the inet_aton() and inet_ntoa() functions.
You can check the official manual.
INET_ATON(expr)
Gives a dot address representation of a network address as a string, and returns an integer representing the value of that address. Addresses can be either 4 or 8 bit addresses.
mysql
>
select inet_ntoa(3507806248);
+-----------------------+
| inet_ntoa(3507806248) |
+-----------------------+
| 209.20.224.40 |
+-----------------------+
1 row in set (0.00 sec)
The resulting Numbers are always in network byte order. As above, the Numbers are calculated as 209×2563 + 207×2562 + 224×2561 + 40 ×2560. Let's check it:
mysql
>
select 209*POW(256,3)+207*POW(256,2)+224*POW(256,1)+40*POW(256,0);
+------------------------------------------------------------+
| 209*POW(256,3)+207*POW(256,2)+224*POW(256,1)+40*POW(256,0) |
+------------------------------------------------------------+
| 3520061480 |
+------------------------------------------------------------+
1 row in set (0.02 sec)
INET_ATON() also understands the short IP address:
mysql
>
select inet_aton('127.0.0.1'),inet_aton('127.1');
+------------------------+--------------------+
| inet_aton('127.0.0.1') | inet_aton('127.1') |
+------------------------+--------------------+
| 2130706433 | 2130706433 |
+------------------------+--------------------+
1 row in set (0.00 sec)
You can understand that the middle 2 is the address and the default is 0.
Note: it is recommended that you use the INT UNSIGNED column when storing values generated by INET_ATON(). If you use the (signed) INT column, the corresponding IP address value for the first 8-bit group greater than 127 will be up to 2147483647 (that is, the value returned by INET_ATON('127.255.255.255 '). Of course, it's easier to use bigint directly.
INET_NTOA(expr)
Given a numeric network address (4 or 8 bits), return the electrical address representation of that address as a string. That's the inverse of inet_aton().
mysql
>
select inet_ntoa(3507806248);
+-----------------------+
| inet_ntoa(3507806248) |
+-----------------------+
| 209.20.224.40 |
+-----------------------+
1 row in set (0.00 sec)