PDA

View Full Version : Parse all IPs from a string



Lonsofore
8th July 2017, 07:48
Hello all. Here is a little script to parse all ip from your string. You can use it to your server messages and find some spamers on your servers (who write something like "connect 123.45.6.7! best server ever!").
Doesn't require libcod.
Returns undefined if there is no IP or an array with list of them.



getIndexesOfEqual(str, char)
{
arr = [];
for (i=0; i<str.size; i++)
{
if (str[i] == char)
arr[arr.size] = i;
}
return arr;
}

parseIPs(str)
{
arr = getIndexesOfEqual(str, ".");

// check, if we have less than 3 dots
if (arr.size < 3)
return undefined;

// check the distance between dots (more than 3 is wrong)
dot1 = [];
dot2 = [];
for (i=2; i<arr.size; i++)
{
if (arr[i-2]>0 && arr[i]<str.size-1 && arr[i]-arr[i-1]<=3 && arr[i-1]-arr[i-2]<=3)
{
dot1[dot1.size] = arr[i-2];
dot2[dot2.size] = arr[i];
}
}

// if there is no dots
if (dot1.size == 0)
return undefined;

ips = [];
for (i=0; i<dot1.size; i++)
{
start = dot1[i];
end = dot2[i];

// save old values
oldstart = start;
oldend = end;

// find real start, end
for (j=0; j<=2; j++)
{
if (start-1>=0 && isInt(str[start-1]))
start--;
if (end+1<str.size && isInt(str[end+1]))
end++;
}

// and check, is start/end is a dot
if (start==oldstart || end==oldend)
continue;

// check all other symbols then
for (j=start; j<end; j++)
{
if (str[j] != "." && !isInt(str[j]))
continue;
}

// save ip
ips[ips.size] = getSubStr(str, start, end+1);
}

if (ips.size == 0)
return undefined;
else
return ips;
}