How To Convert LongIP's to ShortIP's and Vice Versa

IP converting (long/short)
Example:
34753784563 instead of 193.234.22.12

used by different applications like IRC (DCC algorithm)

Converts a LongIP to a ShortIP

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 a ShortIP to a LongIP

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;

 

Share this article!

Follow us!

Find more helpful articles: