现在的位置: 首页 > 综合 > 正文

获取公网IP

2017年09月08日 ⁄ 综合 ⁄ 共 539字 ⁄ 字号 评论关闭

其实说起来,要从本机直接获取公网 IP 是没可能的,必须在访问时,由网络返回 IP,用户才能知道自己的公网 IP 到底是什么。我这段代码也是取了巧的,直接通过公网页面得到 IP,并且返回给调用者。唯一的不足就是使用程序时必须上网(其实也不算不足了,不上网跟本就没 IP,也谈不上公网了)。

代码如下:

function TFormMain.GetIP: string;
var
   xml : OleVariant;
   r:string;
   p1,p2 : Integer;
begin
   xml := CreateOleObject('Microsoft.XMLHTTP');
   xml.Open('GET','http://www.net.cn/static/customercare/yourIP.asp', False);
   xml.Send;
   r := xml.responseText;
   p1:=Pos('<h2>',r); // 找到 h2 标签
   p2:=Pos('</h2>',r);   // 找到 h2 结束标签
   Result := Copy(r, p1+4, p2-p1-4);
end;

http://hi.baidu.com/rarnu/blog/item/94a50d249fecfa29d50742cd.html 

抱歉!评论已关闭.