[转帖]Delphi检测IP地址合法性函数三例

//检测IP地址合法性函数例1:
function IsValidIP(const Value: string): Boolean; //检测IP地址合法性函数
var
Strs: TStrings;
I: Integer;
J: Integer;
begin
Result := False;
Strs := TStringList.Create;
try
     ExtractStrings(['.'], [], PChar(Value), Strs);//以"."为分割, 将值保持到Strs中.
     if Strs.Count <> 4 then Exit; //IP地址没有4段,无效!
     for I := 0 to Strs.Count - 1 do
     begin
        J := StrToIntDef(Strs[I], -1);
        if (I=0) and (J = 0) then Exit//IP地址的第1段不能为0!
        else if (J < 0) or (J > 255) then Exit; //不在0..255范围,无效!
     end;
     Result := True;
 finally
     FreeAndNil(Strs);
end;
end;

//检测IP地址合法性函数例2:
function IsValidIP(Str: string): Boolean;
var
  i, PartCount {用多少段,以点号分开}: Integer;
  Part: string;
begin
  PartCount := 0;
  while Str <> '' do
  begin
    i := Pos('.', Str);
    if i = 0 then
    begin
      Part := Str;
      Str := '';
    end
    else
    begin
      Part := Copy(Str, 1, i - 1);
      Delete(Str, 1, i);
    end;

    //IP分段必须是[0,255]的整数
    if not TryStrToInt(Part, i) or (i < 0) or (i > 255) then
    begin
      Result := False;
      Exit;
    end;
    Inc(PartCount);
  end;

  Result := PartCount = 4; //必须要有4段
end;


uses WinSock;

function IsLegalIP(IP:string):boolean; 
begin 
  if Longword(inet_addr(pchar(IP)))=INADDR_NONE then 
  begin 
    result:=false;
    exit; 
  end 
  else result:=true; 
end;

//检测IP地址合法性函数例3:
  procedure   TFAutoStat.Timer1Timer(Sender:   TObject);   
  begin   
      StatusBar1.Panels.Items[0].Text:=DateToStr(Date())+'   '+TimeToStr(Time());   
      if   (bDoRead=false)   and   (dDoReadTime<>0)   then   
      begin   
          if   TimeToStr(dDoReadTime)=TimeToStr(Time())   then   
          begin   
              ActReadData.Execute();   
              bDoRead:=true;   
          end;   
      end;   
  end;   

posted @ 2010-08-20 10:20  jackal07  阅读(994)  评论(0编辑  收藏  举报