Modul:Nätverk

Från Wikipedia

Dokumentation [visa] [redigera] [historik] [rensa sidcachen]


-- Modul för diverse nätverksrelaterade områden, till exempel identifiering av IP-adresser
jag = {}

-- Källa: http://stackoverflow.com/a/16643628/238978
function GetIPType(ip)
  local R = {ERROR = 0, IPV4 = 1, IPV6 = 2, STRING = 3}
  if type(ip) ~= "string" then return R.ERROR end
 
  -- check for format 1.11.111.111 for ipv4
  local chunks = {ip:match("(%d+)%.(%d+)%.(%d+)%.(%d+)")}
  if #chunks == 4 then
    for _,v in pairs(chunks) do
      if tonumber(v) > 255 then return R.STRING end
    end
    return R.IPV4
  end
 
  -- check for ipv6 format, should be 8 'chunks' of numbers/letters
  local chunks = {ip:match(("([a-fA-F0-9]*):"):rep(8):gsub(":$",""))}
  if #chunks == 8 then
    for _,v in pairs(chunks) do
      if #v > 0 and tonumber(v, 16) > 65535 then return R.STRING end
    end
    return R.IPV6
  end
 
  return R.STRING
end
 
jag.ip = function(frame)
    local ip = frame.args[1]
    local iptype = GetIPType(ip)
    if     iptype == 1 then return "ipv4"
    elseif iptype == 2 then return "ipv6"
    elseif iptype == 3 then return "annan"
    else return "fel"
    end
end

return jag