Storing IP as an unsigned int?

I read that the best way to store IP addresses in a database is to create an Unsigned Int (10) field. How to translate IP addresses using PHP? I tried using

$this->ip = long2ip($_SERVER['REMOTE_ADDR']);

But this does not seem to work. I found a way to convert it back to an IP address using

$this->ip = sprintf("%u", ip2long($result['ip']));

How do I convert the IP address first? Should I use PHP for this? Or would it be better to integrate into a MySQL query?

+3
source share
5 answers

long2ipconverts an integer to IP format and ip2longdoes the opposite.

ip2long $_SERVER['REMOTE_ADDR'] long2ip :

$long = ip2long($_SERVER['REMOTE_ADDR']);
$ip   = long2ip($long);
+12

SQL-:

INSERT INTO `table`
    (`ip`)
VALUES
    INET_ATON('192.168.0.1')

:

SELECT INET_NTOA(`ip`)
    FROM `table`
+12

function ip2int($ip) {
    $a = explode(".",$ip);
    return $a[0] * 256 * 256 * 256 + $a[1] * 256 * 256 + $a[2] * 256 + $a[3];
}
+2

MySQL, INET_ATON (ip2long ) INET_NTOA (long2ip), PHP:

+2

IP- ip2long long2ip. , .

$integer_ip = ip2long($_SERVER["REMOTE_ADDR"]); // => 1113982819
$dotted_ip  = long2ip($integer_ip);             // => "66.102.7.99"
+1

Source: https://habr.com/ru/post/1767311/


All Articles