Sorting IPv4 address with port number

匆匆过客 提交于 2019-12-14 03:57:33

问题


I'm trying to alter an IP address string that has a port number in it so to sort a table, an example IP string:

 IP = "120.88.66.99:075"

I can remove the .'s and the : with:

 IP = string.gsub(IP,'%W',"")

and that gives me 120886699075 but I would like to change the only : to a . so it gives me 120886699.075

Edit:

Actually what I wanted is not working as it does not take in to account the number of numbers between the .'s so what I woulds like is a way to sort the ip in the given format so a table containing the original ip string can be sorted.

Edit 2:

I have this nearly working with this:

 function IPToDec(IPs)
  local t = {}
  local f = "(.-)%."
  local l = 1;
  local s, e, c = IPs:find(f,1)
  while s do
    if s ~= 1 or c ~= "" then
     table.insert(t,c)
    end
    l = e+1;
    s, e, c = IPs:find(f,l)
  end
  if l <= #IPs then
    c = IPs:sub(l)
    table.insert(t,c)
  end
  if(#t == 4) then
    return 16777216*t[1] + 65536*t[2] + 256*t[3] + t[4]
  else
    return -1
  end
 end

 IP = "120.88.66.99:075"
 IP = IPToDec(IP:gsub('%:+'..'%w+',""))

but I'm having to loose the port to get it to sort properly, ideally I would like to include the port number in the sorting because it might be possible that the ip's are coming from the same source but different computers.


回答1:


The most simple solution is to use two patterns:

IP = IP:gsub("%.", ""):gsub(":", ".")

The first gsub replaces . with an empty string, the second one replaces : to .


Using one call to gsub is also possible. Use an auxiliary table as the second argument like this:

 IP = IP:gsub("%W", {["."] = "", [":"] = "."})



回答2:


Both

IP1 = "120.88.11.1:075"
IP2 = "120.88.1.11:075"

will be converted to the same string 12088111.075
Is this what you really need?

Probably, you want the following type of conversion?

IP1 = "120.88.11.1:075" --> 120088011001.075
IP2 = "120.88.1.11:075" --> 120088001011.075

local function IPToDec(IPs)
   -- returns integer from (-1) to (2^48-1)
   local d1, d2, d3, d4, port = IPs:match'^(%d+)%.(%d+)%.(%d+)%.(%d+):?(%d+)$'
   if d1 then
      port = port == '' and 0 or port
      return (((d1*256+d2)*256+d3)*256+d4)*65536+port
   else
      return -1
   end
end

print(string.format('%.16g',IPToDec("120.88.66.99:075")))
print(string.format('%.16g',IPToDec("120.88.66.99")))
print(string.format('%.16g',IPToDec("not an IP")))


来源:https://stackoverflow.com/questions/23654734/sorting-ipv4-address-with-port-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!