Delphi 7获取外网IP地址的实现方法

在Delphi 7中获取外网IP(也称为公共IP)的方法有多种,其中最常见的一种是通过发送HTTP请求来查询公共IP地址。以下是使用Indy组件库实现的方法:

uses
  IdHTTP;
var
  HTTP: TIdHTTP;
  ResponseText: string;
  IPStartPos, IPEndPos: Integer;
begin
  HTTP := TIdHTTP.Create(nil);
  try
    ResponseText := HTTP.Get('http://checkip.dyndns.org');  // 发送GET请求
    IPStartPos := Pos('Address:', ResponseText) + 8;  // 查找IP地址的位置
    IPEndPos := Pos('', ResponseText);  // 查找结束位置
    ShowMessage(Copy(ResponseText, IPStartPos, IPEndPos - IPStartPos));  // 提取并显示外网IP
  finally
    HTTP.Free;
  end;
end;

此代码通过Indy的TIdHTTP组件发送HTTP请求到checkip.dyndns.org,并解析返回的HTML内容,从中提取出公共IP地址。请注意,响应格式可能会变化,需根据实际情况调整解析逻辑。

这种方法的优点是简单易实现,但依赖于外部服务,若该服务不可用,则无法获取IP。

rar
获取外网IP.rar 预估大小:13个文件
folder
获取外网IP 文件夹
folder
控件 文件夹
file
HTTPGet.dcr 472B
file
HTTPGet.pas 12KB
file
GetInternetLocalIP.pas 1011B
file
Functions.pas 4KB
file
Project1.res 876B
file
获取本机IP(内网).txt 1KB
file
GetInternetLocalIP.dfm 662B
file
Unit1.dfm 497B
file
Project1.cfg 362B
file
Project1.dpr 221B
file
Project1.exe 408KB
file
Project1.dof 1KB
file
Unit1.pas 578B
rar 文件大小:181.3KB