2004. december 21., kedd

Find out if IP Address is valid


Problem/Question/Abstract:

Find out if IP Address is valid

Answer:

function IsWrongIP(ip: string): boolean;
var
  z, i: byte;
  st: array[1..3] of byte;
const
  ziff = ['0'..'9'];
begin
  st[1] := 0;
  st[2] := 0;
  st[3] := 0;
  z := 0;
  Result := False;
  for i := 1 to length(ip) do
    if ip[i] in ziff then
    else
    begin
      if ip[i] = '.' then
      begin
        inc(z);
        if z < 4 then
          st[z] := i
        else
        begin
          IsWrongIP := True;
          exit;
        end;
      end
      else
      begin
        IsWrongIP := True;
        exit;
      end;
    end;
  if (z <> 3) or (st[1] < 2) or (st[3] = length(ip)) or (st[1] + 2 > st[2]) or
    (st[2] + 2 > st[3]) or (st[1] > 4) or (st[2] > st[1] + 4) or (st[3] > st[2] + 4) then
  begin
    IsWrongIP := True;
    exit;
  end;
  z := StrToInt(copy(ip, 1, st[1] - 1));
  if (z > 255) or (ip[1] = '0') then
  begin
    IsWrongIP := True;
    exit;
  end;
  z := StrToInt(copy(ip, st[1] + 1, st[2] - st[1] - 1));
  if (z > 255) or ((z <> 0) and (ip[st[1] + 1] = '0')) then
  begin
    IsWrongIP := True;
    exit;
  end;
  z := StrToInt(copy(ip, st[2] + 1, st[3] - st[2] - 1));
  if (z > 255) or ((z <> 0) and (ip[st[2] + 1] = '0')) then
  begin
    IsWrongIP := True;
    exit;
  end;
  z := StrToInt(copy(ip, st[3] + 1, length(ip) - st[3]));
  if (z > 255) or ((z <> 0) and (ip[st[3] + 1] = '0')) then
  begin
    IsWrongIP := True;
    exit;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése