Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

[Delphi] Ip4 Address String To Integer

delphi string

  • Please log in to reply
No replies to this topic

#1 Luthfi

Luthfi

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1320 posts
  • Programming Language:PHP, Delphi/Object Pascal, Pascal, Transact-SQL
  • Learning:C, Java, PHP

Posted 28 April 2012 - 06:39 PM

Got the idea from this code snippet post.

Method 1 (Using record)
type
  PIP4Address=^TIP4Address;
  TIP4Address=packed record
    a: Byte;
    b: Byte;
    c: Byte;
    d: Byte;
  end;

function ToIP4(const a, b, c, d: Byte): Integer;
var
  _Result: TIP4Address absolute Result;
begin
  _Result.a := a;
  _Result.b := b;
  _Result.c := c;
  _Result.d := d;
end;


Method 2 (Using SHL Operations)
function ToIP4(const A, B, C, D: Byte): Integer;
begin
  Result := (A shl 24) + (B shl 16) + (C shl 8) + D;
end;


To convert from dotted IP4 Address string value.
Say you have IP4 address in string format, like this: '192.168.0.1'. You can use code like the following to convert it to integer (note that in turn the following code will use either one shown above).

procedure StringToIP4Addr(const AIP4Str: string): Integer;
var
  S: TStrings;
begin
  S := TStringList.Create;
  try
    S.Delimiter := '.';
    S.DelimitedText := AIP4Str;

    // do preeliminary check. The IP4 Address string must consists of 4 parts. Less or more than that would be invalid values
    if S.Count<>4 then
      raise Exception.Create('Invalid IP4 Address string');

    Result := ToIP4(StrToInt(S[0]), StrToInt(S[1]), StrToInt(S[2]),  StrToInt(S[3]));
  finally
    S.Free;
  end;
end;

  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download