//对两个IP做比较
//IP1<IP2,返回 1
//IP1=IP2,返回 2
//IP1>IP2,返回 3
//若其中一个IP非法,则返回 -1
function IPCompare(const IP1,IP2:String):integer;
var
tmpIP1:String;
tmpIP2:String;
//测试IP地址是否非法
//非法IP地址返回 True
//否则返回False
function InvalidIpAddress(const IPAddress:String):boolean;
var
iPos:Integer;
tmpIP:String;
tmpID:Integer;
begin
Result:=false;
tmpIP:=IPAddress;
//通过StringReplace测试是否存在三个'.'号,否则非法IP
if Length(tmpIP)-Length(StringReplace(tmpIP,'.','',[rfReplaceAll]))<>3 then
begin
Result:=true;
exit;
end;
iPos:=Pos('.',tmpIP);
repeat
try
//将IP地址拆分并转换成数值
//转换失败,非法IP
if iPos<=0 then
tmpID := StrToInt(tmpIP)
else
tmpID := StrToInt(Copy(tmpIP,1,iPos-1));
//测试数值是否0~255之间的数字,否则非法IP
if (tmpID<0) or (tmpID>255) then
raise ERangeError.Create('Invalid IP Address!');
if iPos<=0 then break;
except
Result:=True;
exit;
end;
tmpIP:=Copy(tmpIP,iPos+1,Length(tmpIP)-iPos);
iPos:=Pos('.',tmpIP);
until false;
end;
//将IP地址格式化为每段数字以三位显示的字符串
//例:192.168.0.25
//格式化后成为:192.168.000.025
//非法IP返回空串('')
function FormatIPAddress(const IPAddress:String):string;
var
iPos:Integer;
tmpIP:String;
tmpID:String;
begin
Result:='';
if InvalidIPAddress(IPAddress) then exit;
tmpIP:=IPAddress;
iPos:=Pos('.',tmpIP);
repeat
if iPos<=0 then
begin
tmpID := tmpIP;
while Length(tmpID)<3 do
tmpID:='0'+tmpID;
end
else
begin
tmpID := Copy(tmpIP,1,iPos);
while Length(tmpID)<4 do
tmpID:='0'+tmpID;
end;
Result:=Result+tmpID;
if iPos<=0 then break;
tmpIP:=Copy(tmpIP,
iPos+1,
Length(tmpIP)-iPos);
iPos:=Pos('.',tmpIP);
until false;
end;
begin
Result:=-1;
tmpIP1:=FormatIPAddress(IP1);
if tmpIP1='' then exit;
tmpIP2:=FormatIPAddress(IP2);
if tmpIP2='' then exit;
//CompareString s1,s2
//s1<s2,Result:1
//s1=s2,Result:2
//s1>s2,Result:3
Result:=CompareString(LOCALE_SYSTEM_DEFAULT,
NORM_IGNORECASE,
PChar(tmpIP1),-1,
PChar(tmpIP2),-1);
end;
//测试IPTest是否在IP1与IP2范围内。
function IPInRange(const IPTest,IP1,IP2:string;
const PosCase:Boolean=False):Boolean;
var
tmpValue:Integer;
tmpIPLo:String;
tmpIPHi:String;
begin
Result:=false;
tmpIPLo:=IP1;
tmpIPHi:=IP2
//IP1和IP2是否为固定位置
//即,IP1<=IP2
if not PosCase then
begin
tmpValue:=IPCompare(IP1,IP2);
if tmpValue=-1 then exit;
if tmpValue=3 then
begin
tmpIPLo:=IP2;
tmpIPHi:=IP1
end;
end;
Result:=(IPCompare(IPTest,IP1)>1)
and
(IPCompare(IP2,IPTest)>1);
end;