如何把ngx.var.binary_remote_addr转化成一个整形数字

243 views
Skip to first unread message

coderesty

unread,
Feb 26, 2014, 3:16:55 AM2/26/14
to openresty
如何把ngx.var.binary_remote_addr转化成一个整形数字?
 
 
2014-02-26

coderesty

lhmwzy

unread,
Feb 26, 2014, 3:30:56 AM2/26/14
to open...@googlegroups.com


2014-02-26 16:16 GMT+08:00 coderesty <code...@gmail.com>:
如何把ngx.var.binary_remote_addr转化成一个整形数字?
 
 
2014-02-26

coderesty

--
--
邮件来自列表“openresty”,专用于技术讨论!
订阅: 请发空白邮件到 openresty...@googlegroups.com
发言: 请发邮件到 open...@googlegroups.com
退订: 请发邮件至 openresty+...@googlegroups.com
归档: http://groups.google.com/group/openresty
官网: http://openresty.org/
仓库: https://github.com/agentzh/ngx_openresty
教程: http://openresty.org/download/agentzh-nginx-tutorials-zhcn.html

Lance

unread,
Feb 26, 2014, 3:34:02 AM2/26/14
to open...@googlegroups.com
以前回我的邮件里 agentzh  给过 ffi 的 ip2long 和 long2ip

Lance

lhmwzy

unread,
Feb 26, 2014, 3:40:32 AM2/26/14
to open...@googlegroups.com
function ip2long(ip_addr)
local blocks = check_ip(ip_addr)[2] or error("Invalid IP-Address")
return bor(bor(lshift(blocks[1],24),lshift(blocks[2],16),lshift(blocks[3],8)),blocks[4])
end

Lance

unread,
Feb 26, 2014, 3:44:43 AM2/26/14
to open...@googlegroups.com
ffi这个看起来应该更快吧

local ffi = require "ffi"

module(...)

ffi.cdef[[
    struct in_addr {
        uint32_t s_addr;
    };

    int inet_aton(const char *cp, struct in_addr *inp);
    uint32_t ntohl(uint32_t netlong);

    char *inet_ntoa(struct in_addr in);
    uint32_t htonl(uint32_t hostlong);
]]

function ip2long(ip)
    local inp = ffi.new("struct in_addr[1]")
    if ffi.C.inet_aton(ip, inp) ~= 0 then
        return ffi.C.ntohl(inp[0].s_addr)
    end
    return nil
end

function long2ip(long)
    if type(long) ~= "number" then
        return nil
    end
    local addr = ffi.new("struct in_addr")
    addr.s_addr = ffi.C.htonl(long)
    return ffi.string(ffi.C.inet_ntoa(
addr))
end


Lance

lhmwzy

unread,
Feb 26, 2014, 4:12:53 AM2/26/14
to open...@googlegroups.com
速度上应无太大差异

coderesty

unread,
Feb 26, 2014, 4:15:04 AM2/26/14
to openresty
OK, O(∩_∩)O谢谢
 
2014-02-26

coderesty

发件人:lhmwzy <lhm...@gmail.com>
发送时间:2014-02-26 17:12
主题:Re: [openresty] 如何把ngx.var.binary_remote_addr转化成一个整形数字
收件人:"openresty"<open...@googlegroups.com>
抄送:
Reply all
Reply to author
Forward
0 new messages