求一个函数,判断输入的字符串是否是合法IP

解决方案 »

  1.   

    有很多的,这个比较好一点function IsValidIP(astrIP:String):Boolean;
    var
      iCount:Integer;
      iIPLength:Integer;
      iFieldLength:Integer;
      iFieldStart:Integer;
      iDotCount:Integer;
      strTemp:String;
    begin
      iIPLength:=Length(astrIP);
      if (iIPLength>15)or(iIPLength<7)then
        begin
        Result:=False;//合法IPv4长度在7和15之间
        Exit;
        end;  iDotCount:=0;
      iFieldLength:=0;
      iFieldStart:=1;
      for iCount:=1 to iIPLength do
        begin
        case astrIP[iCount] of
          "0","1","2","3","4","5","6","7","8","9":
             begin
             iFieldLength:=iFieldLength+1;
             if (3<iFieldLength) then
                begin
                Result:=False;//IP的单域长度超过3
                Exit;
                end;
             end;
          "."
             begin
             if 0=iFieldLength then
                begin
                Result:=False;//"."在开头或连续两个".",或在结尾
                Exit;
                end;
             strTemp:=copy(astrIp,iFieldStart,iCount-iFieldStart);
             if(255<StrToInt(strTemp))then
                begin
                Result:=False;//单域值>255
                Exit;
                end;
             iDotCount:=iDotCount+1;
             if 3<iDotCount then
                begin
                Result:=False;//超过4个域 
                Exit;
                end;
             iFieldLength:=0;
             iFieldStart:=iCount+1;
             end;
          else
             begin
             Result:=False;//非法字符 
             Exit;
             end;
        end;   Result:=True;
    end;
      

  2.   

    uses
      IdStack;
    GStack.IsIP(StrIP)