Comparison

util/ip.lua @ 5597:6fe09707c73b

util.ip: Convert IPv4 mapped addresses to hex.
author Kim Alvefur <zash@zash.se>
date Sat, 18 May 2013 13:14:19 +0200
parent 5552:40e7a6cf15ff
child 5599:34e9f237b915
child 7052:306aabf2d57d
comparison
equal deleted inserted replaced
5596:73fea1a87afd 5597:6fe09707c73b
12 local hex2bits = { ["0"] = "0000", ["1"] = "0001", ["2"] = "0010", ["3"] = "0011", ["4"] = "0100", ["5"] = "0101", ["6"] = "0110", ["7"] = "0111", ["8"] = "1000", ["9"] = "1001", ["A"] = "1010", ["B"] = "1011", ["C"] = "1100", ["D"] = "1101", ["E"] = "1110", ["F"] = "1111" }; 12 local hex2bits = { ["0"] = "0000", ["1"] = "0001", ["2"] = "0010", ["3"] = "0011", ["4"] = "0100", ["5"] = "0101", ["6"] = "0110", ["7"] = "0111", ["8"] = "1000", ["9"] = "1001", ["A"] = "1010", ["B"] = "1011", ["C"] = "1100", ["D"] = "1101", ["E"] = "1110", ["F"] = "1111" };
13 13
14 local function new_ip(ipStr, proto) 14 local function new_ip(ipStr, proto)
15 if proto ~= "IPv4" and proto ~= "IPv6" then 15 if proto ~= "IPv4" and proto ~= "IPv6" then
16 return nil, "invalid protocol"; 16 return nil, "invalid protocol";
17 end
18 if proto == "IPv6" and ipStr:find('.', 1, true) then
19 local changed;
20 ipStr, changed = ipStr:gsub(":(%d+)%.(%d+)%.(%d+)%.(%d+)$", function(a,b,c,d)
21 return (":%04X:%04X"):format(a*256+b,c*256+d);
22 end);
23 if changed ~= 1 then return nil, "invalid-address"; end
17 end 24 end
18 25
19 return setmetatable({ addr = ipStr, proto = proto }, ip_mt); 26 return setmetatable({ addr = ipStr, proto = proto }, ip_mt);
20 end 27 end
21 28