核心提示:调用代码示例:varip: string;beginwith TStringlist.Create dotryText := GetHTML('www.whatismyip.com/automatio...
调用代码示例:
var
ip: string;
begin
with TStringlist.Create do
try
Text := GetHTML('www.whatismyip.com/automation/n09230945.asp') ;
if Count > 0 then ip := Strings[Count - 1];
finally
Free;
end;
ShowMessage('Your (gateway / router / proxy) IP address is ' + ip) ;
end;
GetHTML函数代码:
uses ScktComp;
function GetHTML(const AURL: string): string;
var
sHead,sHost,sPage: string;
x,xCnt,xCntTotal: integer;
sock: TClientSocket;
ws: TWinSocketStream;
ss: TStringStream;
buff: array[0..4095] of char;
const
CrLf = #13#10;
begin
Result := '';
sHost := AURL;
x := Pos('//',sHost) ;
if x > 0 then
System.Delete(sHost,1,x+1) ;
x := Pos('/',sHost) ;
if x > 0 then
begin
sPage := Copy(sHost,x,Length(sHost)) ;
System.Delete(sHost,x,Length(sHost)) ;
end
else
begin
sPage := '/';
end;
sock := TClientSocket.Create(nil) ;
try
try
sock.ClientType := ctBlocking;
sock.Port := 80;
sock.Host := sHost;
sock.Open;
// set timeout to 20 seconds
ws := TWinSocketStream.Create(sock.Socket,20000) ;
ss := TStringStream.Create('') ;
try
sHead := 'GET ' + sPage + ' HTTP/1.0 ' + CrLf + 'Host: ' + sHost + CrLf + CrLf;
StrPCopy(buff,sHead) ;
ws.Write(buff,Length(sHead) + 1) ;
ws.Position := 0;
FillChar(buff,SizeOf(buff),0) ;
repeat
xCnt := ws.Read(buff,SizeOf(buff)) ;
xCntTotal := xCntTotal + xCnt;
ss.Write(buff[0],xCnt) ;
until xCnt = 0;
Result := ss.DataString;
finally
ws.Free;
ss.Free;
end;
except
end;
finally
sock.Free;
end;
end;