DELPHI 如何获取外网ip
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DELPHI 如何获取外网ip相关的知识,希望对你有一定的参考价值。
如题。把获取的IP放在edit 点击button可以复制获取的IP
可以办到吗?
一楼的方法不太懂啊。郁闷 。需要那些控件 函数类的我一点都不懂啊
function pro_result(str:string):string ;//封装了成一个匹配字符的处理函数
var
i_0,i_1:Integer;
flag:Boolean;
str_1,temp_result:string;
begin
temp_result:='';
while Pos('查询结果',str)<>0 do
begin
i_1:=Pos('</span>',str);
i_0:=Pos('查询结果',str);
temp_result:=temp_result+Copy(str,i_0,i_1-i_0)+#13#10;
Delete(str,1,Pos('</span>',str));
end;
temp_result:=StringReplace(temp_result,' ','',[rfreplaceall,rfignorecase]);
Result:=temp_result;
end;
上面这段代码要放在那里?
function pro_result(str:string):string ;//封装了成一个匹配字符的处理函数
var
i_0,i_1:Integer;
flag:Boolean;
str_1,temp_result:string;
begin
temp_result:='';
while Pos('查询结果',str)<>0 do
begin
i_1:=Pos('</span>',str);
i_0:=Pos('查询结果',str);
temp_result:=temp_result+Copy(str,i_0,i_1-i_0)+#13#10;
Delete(str,1,Pos('</span>',str));
end;
temp_result:=StringReplace(temp_result,' ','',[rfreplaceall,rfignorecase]);
Result:=temp_result;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
temp,str_1,str_2:string;
i:Integer;
begin
Memo1.Text:=IdHTTP1.Get('http://www.ipseeker.cn');
temp:=Memo1.Text;
i:=Pos('查询结果',temp);
str_1:=Copy(temp,i,254);
str_2:=pro_result(str_1);
Memo2.Text:=str_2;
end;
如果自己有ASP空间的话更方便
你找一个ASP的空间,上面写一个ASP程序,再用INDY的http组件访问这个ASP程序就有本机的外网IP了!
这个ASP程序如下:
<html>
<%
sip=Request.ServerVariables("LOCAL_ADDR")
cip=Request.ServerVariables("REMOTE_ADDR")
%>
<body>
IP=<%=cip%>
</body>
</html>
调用:
procedure TForm1.Button1Click(Sender: TObject);
begin
WebBrowser1.Navigate('www.xxx.cn/ip.asp');
edit1.Text:=IdHTTP1.Get('http://www.xxx.cn/ip.asp');
end; 参考技术A 拷了一段代码应该不错
注意: 程序必须运行在直接拨号联网的用户,不适用于内网用户。
//常量定义
Const
MAX_HOSTNAME_LEN = 128;
MAX_DOMAIN_NAME_LEN = 128;
MAX_SCOPE_ID_LEN = 256;
MAX_ADAPTER_NAME_LENGTH = 256;
MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
MAX_ADAPTER_ADDRESS_LENGTH = 8;
//定义相关结构
Type
TIPAddressString = Array[0..4*4-1] of Char;
PIPAddrString = ^TIPAddrString;
TIPAddrString = Record
Next : PIPAddrString;
IPAddress : TIPAddressString;
IPMask : TIPAddressString;
Context : Integer;
End;
PFixedInfo = ^TFixedInfo;
TFixedInfo = Record FIXED_INFO
HostName : Array[0..MAX_HOSTNAME_LEN+3] of Char;
DomainName : Array[0..MAX_DOMAIN_NAME_LEN+3] of Char;
CurrentDNSServer : PIPAddrString;
DNSServerList : TIPAddrString;
NodeType : Integer;
ScopeId : Array[0..MAX_SCOPE_ID_LEN+3] of Char;
EnableRouting : Integer;
EnableProxy : Integer;
EnableDNS : Integer;
End;
PIPAdapterInfo = ^TIPAdapterInfo;
TIPAdapterInfo = Record IP_ADAPTER_INFO
Next : PIPAdapterInfo;
ComboIndex : Integer;
AdapterName : Array[0..MAX_ADAPTER_NAME_LENGTH+3] of Char;
Description : Array[0..MAX_ADAPTER_DESCRIPTION_LENGTH+3] of Char;
AddressLength : Integer;
Address : Array[1..MAX_ADAPTER_ADDRESS_LENGTH] of Byte;
Index : Integer;
_Type : Integer;
DHCPEnabled : Integer;
CurrentIPAddress : PIPAddrString;
IPAddressList : TIPAddrString;
GatewayList : TIPAddrString;
DHCPServer : TIPAddrString;
HaveWINS : Bool;
PrimaryWINSServer : TIPAddrString;
SecondaryWINSServer : TIPAddrString;
LeaseObtained : Integer;
LeaseExpires : Integer;
End;
type
TGetAdaptersInfo=function(AI : PIPAdapterInfo; Var BufLen : Integer) : Integer;StdCall;
var
GetAdaptersInfo:TGetAdaptersInfo;
h:hmodule;
implementation
function Loadiphlpapidll:boolean;//动态加载iphlpapi.dll中的GetAdaptersInfo
begin
if h>0 then exit;
h:=Loadlibrary('iphlpapi.dll');
if h>0 then
GetAdaptersInfo:=GetProcAddress(h,'GetAdaptersInfo');
result:=assigned(GetAdaptersInfo);
end;
function GetWanIP: string;//获取外网IP
Var
AI,Work : PIPAdapterInfo;
Size : Integer;
Res : Integer;
Description:string;
WanIP:string;
Function GetAddrString(Addr : PIPAddrString) : String;
Begin
Result := '';
While (Addr <> nil) do Begin
Result := Result+'A: '+Addr^.IPAddress+' M: '+Addr^.IPMask+#13;
Addr := Addr^.Next;
End;
End;
begin
Loadiphlpapidll;
result:='无法获得外网IP';
Size := 5120;
GetMem(AI,Size);
Res := GetAdaptersInfo(AI,Size);
If (Res <> ERROR_SUCCESS) Then
Begin
MessageBoxA(0,'获取外网IP失败 ','错误',MB_OK or MB_ICONERROR);
exit;
End;
Work := AI;
Repeat
Description:=strpas(Work^.Description);
if pos('WAN',Description)>0 then
begin
WanIP:=GetAddrString(@Work^.IPAddressList);
//这里返回的WanIP是这种格式 A: 222.111.25.32 M: 255.255.255.0
//其中A到M中间就是外网IP了
WanIP:=copy(WanIP,pos(':',WanIP)+1,pos('M',WanIP)-pos(':',WanIP)-2);
result:=trim(WanIP);//这里就是最终的外网IP了
exit;
end;
Work := Work^.Next;
Until (Work = nil);
FreeMem(AI);
end; 参考技术B 一楼的方法就是通过与一个外网的web服务通讯,建立通讯的过程就可以让对方告知自己的IP。与查自己新买的手机号的办法类似,用新号码打给同学,让他告诉你。 参考技术C 可以用udp发信息,服务器端收到的ip都是真实的。其他的方式都不好。 参考技术D 网上也只有楼上这个办法了
C# 获取本机外网IP
我想获取本机的外网IP(桌面应用程序)
Dns类里有个GetHostEntry方法能获取IP!
但是获取的是个列表,里面有外网IP,也有内网ip!
我试着把内网IP过滤掉(有10开头的,192.168开头,172.16-172.31开头)
可是又蹦出一个169.254开头的本地IP!
我不想用过滤了,感觉不太保险!
怎么直接获取本机的外网IP?用windows Api也行
using System.Runtime.InteropServices ;
using System.Collections.Generic ;
using System.Net ;
using System.Net.Sockets ;
using System.IO ;
using ESBasic.Helpers ;
using ESBasic.Network.Tcp;
namespace ESBasic.Network
/// <summary>
/// NetHelper 。
/// </summary>
public static class NetHelper
#region IsPublicIPAddress
public static bool IsPublicIPAddress(string ip)
if(ip.StartsWith("10.")) //A类 10.0.0.0到10.255.255.255.255
return false ;
if(ip.StartsWith("172."))//B类 172.16.0.0到172.31.255.255
if(ip.Substring(6 ,1) == ".")
int secPart = int.Parse(ip.Substring(4 ,2)) ;
if((16 <= secPart) && (secPart <= 31) )
return false ;
if(ip.StartsWith("192.168."))//C类 192.168.0.0到192.168.255.255
return false ;
return true ;
#endregion
#region ReceiveData
/// <summary>
/// ReceiveData 从网络读取指定长度的数据
/// </summary>
public static byte[] ReceiveData(NetworkStream stream ,int size)
byte[] result = new byte[size] ;
NetHelper.ReceiveData(stream ,result ,0 ,size) ;
return result ;
/// <summary>
/// ReceiveData 从网络读取指定长度的数据 ,存放在buff中offset处
/// </summary>
public static void ReceiveData(NetworkStream stream ,byte[] buff ,int offset ,int size)
int readCount = 0 ;
int totalCount = 0 ;
int curOffset = offset ;
while(totalCount < size)
int exceptSize = size - totalCount ;
readCount = stream.Read(buff ,curOffset ,exceptSize) ;
if(readCount == 0)
throw new IOException("NetworkStream Interruptted !") ;
curOffset += readCount ;
totalCount += readCount ;
/// <summary>
/// ReceiveData 从网络读取指定长度的数据
/// </summary>
public static byte[] ReceiveData(ISafeNetworkStream stream ,int size)
byte[] result = new byte[size] ;
NetHelper.ReceiveData(stream ,result ,0 ,size) ;
return result ;
/// <summary>
/// ReceiveData 从网络读取指定长度的数据 ,存放在buff中offset处
/// </summary>
public static void ReceiveData(ISafeNetworkStream stream, byte[] buff, int offset, int size)
int readCount = 0 ;
int totalCount = 0 ;
int curOffset = offset ;
while(totalCount < size)
int exceptSize = size - totalCount ;
readCount = stream.Read(buff ,curOffset ,exceptSize) ;
if(readCount == 0)
throw new IOException("NetworkStream Interruptted !") ;
curOffset += readCount ;
totalCount += readCount ;
#endregion
#region GetRemotingHanler
//前提是已经注册了remoting通道
public static object GetRemotingHanler(string channelTypeStr ,string ip ,int port ,string remotingServiceName ,Type destInterfaceType)
try
string remoteObjUri = string.Format("0://1:2/3" ,channelTypeStr ,ip ,port ,remotingServiceName) ;
return Activator.GetObject(destInterfaceType ,remoteObjUri);
catch
return null ;
#endregion
#region GetLocalIp
/// <summary>
/// GetLocalIp 获取本机的IP地址
/// </summary>
public static IPAddress[] GetLocalIp()
string hostName = Dns.GetHostName() ;
IPHostEntry hEntry = Dns.Resolve(hostName) ;
return hEntry.AddressList ;
public static IPAddress GetFirstLocalIp()
string hostName = Dns.GetHostName();
IPHostEntry hEntry = Dns.Resolve(hostName);
return hEntry.AddressList[0];
/// <summary>
/// GetLocalPublicIp 获取本机的公网IP地址
/// </summary>
public static string GetLocalPublicIp()
IPAddress[] list = NetHelper.GetLocalIp();
foreach(IPAddress ip in list)
if(NetHelper.IsPublicIPAddress(ip.ToString()))
return ip.ToString() ;
return null ;
#endregion
#region IsConnectedToInternet
/// <summary>
/// IsConnectedToInternet 机器是否联网
/// </summary>
public static bool IsConnectedToInternet()
int Desc=0;
return InternetGetConnectedState(Desc,0);
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(int Description,int ReservedValue);
#endregion
#region GetMacAddress 获取网卡mac地址
/// <summary>
/// GetMacAddress 获取本机所有网卡的Mac地址
/// </summary>
public static IList<string> GetMacAddress()
return MachineHelper.GetMacAddress();
#endregion
#region DownLoadFileFromUrl
/// <summary>
/// DownLoadFileFromUrl 将url处的文件下载到本地
/// </summary>
public static void DownLoadFileFromUrl(string url ,string saveFilePath)
FileStream fstream = new FileStream(saveFilePath ,FileMode.Create ,FileAccess.Write);
WebRequest wRequest = WebRequest.Create(url);
try
WebResponse wResponse = wRequest.GetResponse();
int contentLength =(int)wResponse.ContentLength;
byte[] buffer = new byte[1024];
int read_count = 0 ;
int total_read_count = 0 ;
bool complete = false;
while (!complete )
read_count = wResponse.GetResponseStream().Read(buffer,0,buffer.Length);
if(read_count > 0)
fstream.Write(buffer ,0 ,read_count) ;
total_read_count += read_count ;
else
complete = true ;
fstream.Flush() ;
finally
fstream.Close() ;
wRequest = null;
#endregion
这个类直接拿去用吧,命名空间改一下,里面有你想要的方法以及一些可能对你有用的方法 参考技术A 不可以直接获取外网IP的。除非你本身就是拨号上网,没有通过家用路由器分接。
http://zhidao.baidu.com/question/149330561.html
这个问题我也回答过了% 参考技术B 我也遇到这个问题 求解决方法
以上是关于DELPHI 如何获取外网ip的主要内容,如果未能解决你的问题,请参考以下文章