|
1.正则表达式法
这个函数可以判断一个字符串是否IP地址,配合正则表达式。 正则表达式类下载地址:http://www.delphifans.com/SoftView/SoftView_500.html uses RegExpr; //如果是IP地址返回True,否则,返回False function ISIPAddr(St:string):Boolean; var Sar:array[1..4] of string; St:string; I:Integer; j:Integer; NOIP:Boolean; begin Result:=ExecRegExpr ('^/s*(/d{3}|/d{2}|/d{1})/.(/d{3}|/d{2}|/d{1})/.(/d{3}|/d{2}|/d{1})/.(/d{3}|/d{2}|/d{1})/s*$', st); if Result then begin for J:=1 to 3 do begin I:=Pos('.',st); Sar[J]:=Copy(st,1,I-1); St:=Copy(st,I+1,Length(St)-I); end; Sar[4]:=St; end; for J:=1 to 4 do begin if StrToInt(Sar[J])>255 then begin Result:=False; Break; end; end; end;
2.函数
(一)
function TForm1.IsIPString(IPStr: string): Boolean; var i,DotNum:integer; Tmpstr:string; begin Result:=true; DotNum:=0; for i:=1 to Length(IPStr) do Case IPStr[i] of '0'..'9','.': begin if IPStr[i]<>'.' then begin Tmpstr:=Tmpstr+IPStr[i]; if StrtoInt(tmpstr)>255 then begin Result:=False; exit; end; end else begin if (TmpStr='')and(DotNum>0) then //如果连续2个点的情况 begin Result:=False; Exit; end; Tmpstr:=''; DotNum:=DotNum+1; end; end; else begin Result:=false; exit; end; end; if DotNum<>3 then Result:=False; end;
(二)
function IsValidIP(const IP: string): Boolean; { 判断字符串IP是否是一个合法的IP地址? 是,返回True,否则返回False } var Ar: TStringDynArray; i: integer; begin result := False; Ar := SplitString(IP, '.'); if Length(Ar) <> 4 then Exit; for i := Low(Ar) to High(Ar) do try if not (StrToInt(Ar[i]) in [0..255]) then Exit; except Exit; end; result := True; end;
3.winsock方法
uses winsock
...
if inet_addr(pchar(ip)) = -1 then showmessage('非法IP') else showmessage('合法IP'); |