mysql long to ip,在MySQL中将IP转换为Long

I'm trying to use the ip2country table to show the country flags of the users on my website.

The simplest thing I came up with is to write an SQL statement that takes the users from the session table and queries to see if their respective IP is in a certain range to figure out their country/flag.

It's simple but also dangerous, because when there are 300 users online to show and I fetch them from the session table, querying their countries to display the flags, there will surely be a big memory usage.

Now I tried this to do it in one single query:

SELECT

s.session_ip,

ipc.*

FROM

session AS s

LEFT JOIN ip2country AS ipc

ON ipc.ip_lo <= s.session_ip AND ipc.ip_hi >= s.session_ip

WHERE

s.session_time > '".( time() - 60) )."'

Now it's clear that the above query is wrong because the IPs saved in the ip2country table is an integer, e.g. 1000013824, and the IPs stored in the session table are the string representations of the IPs, e.g. 193.169.0.0

I know how to convert from an IP to a long in PHP with the ip2long(), but is there any equivalent method in MySQL so I don't have to do two queries?

解决方案

SELECT INET_NTOA(1000013824) -> 59.155.0.0

SELECT INET_ATON('193.169.0.0') -> 3249078272

Enjoy :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值