Mirror

Convert long IP addresses to short ones and vice versa (Views: 102)

Problem/Question/Abstract:

How to convert long IP addresses to short ones and vice versa

Answer:

IP converting (long/ short). Example: 34753784563 instead of 193.234.22.12, used by different applications like IRC (DCC algorithm):

Convert long IP addresses to short ones:

function shortIP(const s: string): string;
var
Ip: int64;
a, b, c, d: Byte;
begin
IP := StrToInt64(s);
a := (IP and $FF000000) shr 24;
b := (IP and $00FF0000) shr 16;
c := (IP and $0000FF00) shr 8;
d := (IP and $000000FF);
Result := Format('%d.%d.%d.%d', [a, b, c, d]);
end;

Convert short IP addresses to long ones:

function LongIP(IP: string): string;
var
IPaddr: array[1..4] of Word;
Temp: string;
Res: DWord;
I: Integer;
begin
Temp := IP + '.';
for I := 1 to 4 do
begin
try
IPaddr[i] := StrToInt(copy(Temp, 1, pos('.', Temp) - 1));
Delete(temp, 1, pos('.', Temp));
if (IPaddr[i] > 255) then
raise Exception.Create('');
except
{Check the IP}
result := 'Invalid IP address.';
Exit;
end;
end;
Res := (ipaddr[1] shl 24) + ipaddr[1] + (ipaddr[2] shl 16) + ipaddr[2] +
(ipaddr[3] shl 8) + ipaddr[3] + (ipaddr[4]);
Result := Format('%u', [res]);
end;



<< Back to main page