使用端口号对IPv4地址进行排序 [英] Sorting IPv4 address with port number
问题描述
我正在尝试更改其中包含端口号的IP地址字符串,以便对表进行排序,例如IP字符串示例:
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',"")
这给了我120886699075
,但是我想将唯一的:
更改为.
,所以它给了我120886699.075
and that gives me 120886699075
but I would like to change the only :
to a .
so it gives me 120886699.075
实际上,我想要的是不起作用,因为它没有考虑.之间的数字,所以我想要的是一种按给定格式对ip进行排序的方法,因此包含原始ip的表字符串可以排序.
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.
我几乎可以与此相关:
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+',""))
但是我必须放松端口以使其正确排序,理想情况下,我想在排序中包括端口号,因为IP可能来自相同的来源,但来自不同的计算机. /p>
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.
推荐答案
最简单的解决方案是使用两种模式:
The most simple solution is to use two patterns:
IP = IP:gsub("%.", ""):gsub(":", ".")
第一个gsub
用空字符串替换.
,第二个将:
替换为.
The first gsub
replaces .
with an empty string, the second one replaces :
to .
也可以使用一个呼叫gsub
.使用辅助表作为第二个参数,如下所示:
Using one call to gsub
is also possible. Use an auxiliary table as the second argument like this:
IP = IP:gsub("%W", {["."] = "", [":"] = "."})
这篇关于使用端口号对IPv4地址进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!