16,748
社区成员
发帖
与我相关
我的任务
分享
Function GetIPRange(const IP, Mask: String): String;
function IPToVaule(const IP: String): Cardinal;
var
Str: String;
I, P1, P2: Integer;
begin
P1 := 1;
Result := 0;
for I := 1 to 4 do
begin
if I < 4 then
P2 := Pos('.', IP, P1)
else
P2 := Length(IP) + 1;
Str := Copy(IP, P1 , P2 - P1);
Result := (Result Shl 8) + Byte(StrToInt(Str));
P1 := P2 + 1;
end;
end;
function VauleToIP(const Value: Cardinal): String;
var
PB: PByte;
I: Integer;
begin
Result := '';
PB := @Value;
for I := 3 downto 0 do
begin
Result := Result + IntToStr(PB[I]);
if I > 0 then Result := Result + '.';
end;
end;
var
IPValue, MaskValue, FirstIPValue, LastIPValue: Cardinal;
begin
IPValue := IPToVaule(IP );
MaskValue := IPToVaule(Mask);
FirstIPValue := IPValue and MaskValue;
LastIPValue := FirstIPValue + (not MaskValue);
Result := VauleToIP(FirstIPValue) + ' - ' + VauleToIP(LastIPValue );
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ShowMessage(GetIPRange('192.168.180.101', '255.255.192.0'));
end;
type
{ 定义IP结构 }
TIp = record
a1 : BYTE;
a2 : BYTE;
a3 : BYTE;
a4 : BYTE;
end;
function longToIP(IntIp: Cardinal; BigEndian: Boolean): string;
var
Ip: TIp;
begin
Ip := TIp(IntIp);
case BigEndian of
False : Result := Format('%d.%d.%d.%d', [Ip.a4, Ip.a3, Ip.a2, Ip.a1]);
True : Result := Format('%d.%d.%d.%d', [Ip.a1, Ip.a2, Ip.a3, Ip.a4]);
end;
end;
//聚合IP转起止IP
function cidrIpToIpList(ip: string; mask: integer): TStrings;
var
i,n: integer;
startIp: Cardinal;
begin
startIp:= IpToLong(ip);
result := TStringList.Create;
n := Round(Power(2,32-mask));
result.Add(longToIp(startIp+0));
result.Add(longToIp(startIp+n-1));
end;
function VauleToIP(const Value: Cardinal): String;
var
Bytes: array[0..3] of Byte;
begin
Move(Value, Bytes, 4);
Result := Format('%d.%d.%d.%d',[Bytes[3], Bytes[2], Bytes[1], Bytes[0]]);
end;
function GetIPRange(const IP, Mask: String): String;
function IPToVaule(IP: String): Cardinal;
var
Str: String;
I, Len, P: Integer;
begin
Len := Length(IP);
Result := 0;
for I := 1 to 4 do
begin
if I < 4 then
P := Pos('.', IP)
else
P := Length(IP) + 1;
Str := Copy(IP, 1, P-1);
Result := (Result Shl 8) + Byte(StrToInt(Str));
IP := Copy(IP, P+1, Len);
end;
end;
function VauleToIP(const Value: Cardinal): String;
var
PB: PByte;
I: Integer;
begin
Result := '';
PB := @Value;
for I := 3 downto 0 do
begin
Result := Result + IntToStr((PB+I)^);
if I > 0 then Result := Result + '.';
end;
end;
var
IPValue, MaskValue, FirstIPValue, LastIPValue: Cardinal;
begin
IPValue := IPToVaule(IP );
MaskValue := IPToVaule(Mask);
FirstIPValue := IPValue and MaskValue;
LastIPValue := FirstIPValue + (not MaskValue);
Result := VauleToIP(FirstIPValue) + ' - ' + VauleToIP(LastIPValue );
end;
procedure TForm3.FormCreate(Sender: TObject);
begin
ShowMessage(GetIPRange('192.168.180.101', '255.255.192.0'));
end;