如何将IP地址转换为Lua的整数?

时间:2011-11-20 08:06:57

标签: string lua integer ip

在Lua中,我如何将包含IP地址的字符串转换为整数?

3 个答案:

答案 0 :(得分:20)

我认为IPv4?以及如何将它作为整数? 也许:

local str = "127.0.0.1"
local o1,o2,o3,o4 = str:match("(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)" )
local num = 2^24*o1 + 2^16*o2 + 2^8*o3 + o4

答案 1 :(得分:0)

其他方法可能是:

local addr = "127.0.0.1"
local num = 0
addr:gsub("%d+", function(s) num = num * 256 + tonumber(s) end)

答案 2 :(得分:0)

我提供了两种解决方案。

  • 解决方案1 ​​:没有Lua Bit操作。速度很慢,但是不需要任何外部lua库和.so或.dll文件。
  • 解决方案2 :当您频繁调用这些函数时,性能非常好。在位级别对数字执行运算非常快。

解决方案1:

function ip2dec(ip) local i, dec = 3, 0; for d in string.gmatch(ip, "%d+") do dec = dec + 2 ^ (8 * i) * d; i = i - 1 end; return dec end

function dec2ip(decip) local divisor, quotient, ip; for i = 3, 0, -1 do divisor = 2 ^ (i * 8); quotient, decip = math.floor(decip / divisor), math.fmod(decip, divisor); if nil == ip then ip = quotient else ip = ip .. "." .. quotient end end return ip end

解决方案2:

http://bitop.luajit.org/install.html

http://bitop.luajit.org/download.html

https://github.com/fengpeiyuan/ipconv

package.path  = package.path  .. ";/home/balaji/lualib/bitopt.lua"

package.cpath = package.cpath .. ";/home/balaji/lualib/bit.so"

local bit = require("bitopt")

function dec2ip(dec) return bit:band(bit:rshift(dec, 24), 0xFF) .. "." .. bit:band(bit:rshift(dec, 16), 0xFF) .. "." .. bit:band(bit:rshift(dec, 8), 0xFF) .. "." .. bit:band(dec, 0xFF) end

function ip2dec(ip) local dec = 0; for d in string.gmatch(ip, "%d+") do dec = d + bit:lshift(dec, 8) end; return dec end