您现在的位置:首页 >> 网络通讯 >> 网络通讯 >> 内容

Delphi中通过TClientSocket获取公网(WAN)IP地址

时间:2011/9/3 15:12:17 点击:

  核心提示:调用代码示例: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;

作者:站长 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号