Einzelnen Beitrag anzeigen

Reinhard Kern

Registriert seit: 22. Okt 2006
772 Beiträge
 
#8

Re: Optimierung von, IP-Addresse auf Gültigkeit überprüfen

  Alt 10. Jan 2010, 15:27
Hallo,

als Embedded-Programmierer sieht so etwas ganz abders aus als von den Höhen der VCL, daher folgt die Funktion unten einem ganz naderen Ansatz, nämlich einer Mealy-Maschine - allerdings ist die sehr einfach mit nur einer Bearbeitungsroutine, weil ja alle Bytes bei IP gleichbehandelt werden. Ist aber ohne OO und ohne VCL, nur einfach und schnell, also VCL-Fanatiker ab hier nicht mehr weiterlesen. Dafür funktioniert das auch mit Embedded Pascal auf irgendeinem µC.

Delphi-Quellcode:
program isip2test;

{$APPTYPE CONSOLE}

uses
  SysUtils,windows;
type ShortString = string[255];

function IsIP (s: ShortString): Boolean; { Mealy Machine }
type TIPV4status = (ip_byte1,ip_byte2,ip_byte3,ip_byte4,ip_done);
var MMStatus : TIPV4status;
    nch : char;
    ByteVal : integer;
    ByteSum : integer;
    index : integer;
    IPError : boolean;

  function getnextchar : char;
  begin
  Result := chr(0);
  if index <= length (s) then Result := s[index];
  index := index + 1;
  end;

  procedure OnBytex;
  begin
  if (nch >= '0') and (nch <= '9') then
      ByteVal := ByteVal * 10 + ord (nch) - 48
    else if nch = '.then
         begin
         if ByteVal > 255 then
           IPError := true else ByteSum := ByteSum + ByteVal;
         ByteVal := 0;
         Inc (MMStatus);
         end
      else
        begin
        if MMStatus < ip_byte4 then IPError := true
          else if ByteVal > 255 then IPError := true
            else ByteSum := ByteSum + ByteVal;
        MMStatus := ip_done;
        end;
  end;

begin { isip... }
IPError := false;
MMStatus := ip_byte1;
index := 1;
ByteVal := 0;
ByteSum := 0;
repeat
  nch := getnextchar;
  if MMStatus < ip_done then OnBytex;
until MMStatus = ip_done;
if ByteSum = 0 then IPError := true; { 0.0.0.0 }
if index <= length (s) then IPError := true; { garbage follows }
Result := not IPError;
  {write (s);
  if Result then writeln (' ok') else writeln (' not ok');
  readln;  }

end;

var
  Start: DWORD;
  i: integer;
  b: boolean;
begin
  Start := GetTickCount;
  for i := 0 to 1000000 do begin
    b := IsIP('0.1.2.3');
    b := IsIP('255.255.255.255');
    b := IsIP('1.1.1.255');
    b := IsIP('0.0.0.0');
    b := IsIP('555.3.2.1');
    b := IsIP('555.3.xyz');
    b := IsIP('1.b.1.1');
    b := IsIP('a');
    b := IsIP('');
    b := IsIP('1.0.0.0');
    b := IsIP('10.73.10.108');
    b := IsIP('0.0.1.0');
    b := IsIP('0.1.1.0 xyz');
    b := IsIP('1.0.0.0');
  end;
  writeln(IntToStr(GetTickCount - Start));
  readln;
end.
Gruss Reinhard
  Mit Zitat antworten Zitat