将 IP 存储为无符号整数?

发布于 2024-09-25 16:08:42 字数 326 浏览 0 评论 0原文

我读到在数据库中存储 IP 地址的最佳方法是创建一个 Unsigned Int(10) 字段。如何使用 PHP 转换 IP 地址?我尝试过使用

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

但这似乎不起作用。我找到了将其转换回 IP 地址的方法,使用

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

如何最初转换 IP 地址?我应该为此使用 PHP 吗?或者集成到MySQL查询中会更好吗?

I read that the best way to store IP addresses in a database is to make an Unsigned Int(10) field. How do I convert the IP addresses using PHP? I've tried using

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

But this doesn't seem to work. I found the way to convert it back to an IP address using

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

How do I convert the IP Address initially? Should I be using PHP for this? Or would it be better to integrate into the MySQL query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

壹場煙雨 2024-10-02 16:08:42

long2ip 将整数转换为 IP 格式,并 ip2long 则相反。

因此,使用ip2long$_SERVER['REMOTE_ADDR']转换为整数以将其存储在数据库中,并在读取该整数后使用long2ip数据库:

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

long2ip converts an integer into the IP format and ip2long does the inverse.

So use ip2long to convert $_SERVER['REMOTE_ADDR'] into an integer for storing it in the database and use long2ip after reading the integer from the database:

$long = ip2long($_SERVER['REMOTE_ADDR']);
$ip   = long2ip($long);
彼岸花似海 2024-10-02 16:08:42

最好将此逻辑放入 SQL 查询中:

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

然后在选择数据时隐藏地址:

SELECT INET_NTOA(`ip`)
    FROM `table`

Better put this logic in your SQL query:

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

And then covert address back when selecting data:

SELECT INET_NTOA(`ip`)
    FROM `table`
故人爱我别走 2024-10-02 16:08:42

我用过这个

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

I used this

function ip2int($ip) {
    $a = explode(".",$ip);
    return $a[0] * 256 * 256 * 256 + $a[1] * 256 * 256 + $a[2] * 256 + $a[3];
}
箹锭⒈辈孓 2024-10-02 16:08:42

如果您使用 MySQL,则可以使用 INET_ATON (ip2long 等效项)和 INET_NTOA (long2ip) 函数,而不是使用 PHP 进行处理:

If you're using MySQL you can use the INET_ATON (ip2long equivalent) and INET_NTOA (long2ip) functions rather than doing the processing with PHP:

随遇而安 2024-10-02 16:08:42

您需要使用 ip2long 转换 IP 的点分字符串版本,然后使用 long2ip 返回。看起来你现在已经倒退了。

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

You’ll want to convert the dotted string version of your IP using ip2long, and back using long2ip. Looks like you have it backwards right now.

$integer_ip = ip2long($_SERVER["REMOTE_ADDR"]); // => 1113982819
$dotted_ip  = long2ip($integer_ip);             // => "66.102.7.99"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文