C和MFC巧妙获取外网IP的两种实现方法
本文以C与MFC的两个实例详述了取外网IP的两种实现方法,具体实现代码如下:
MFC语言实现获取外网IP:
#include<windows.h>
#include<urlmon.h>
#pragmacomment(lib,"URLMON.lib")
voidmain()
{
URLDownloadToFile(NULL,"http://www.ip138.com/ip2city.asp","ip.txt",0,NULL);
system("notepadip.txt");
}
#include<urlmon.h>
#pragmacomment(lib,"Urlmon.lib")
charbuf[MAX_PATH]={0};
charchTempIp[128];
charchIP[64];
URLDownloadToFile(0,"http://www.ip138.com/ip2city.asp","c:\\1.ini",0,NULL);
FILE*fp=fopen("c:\\1.ini","r");
if(fp!=NULL)
{
fseek(fp,0,SEEK_SET);
fread(buf,1,256,fp);
fclose(fp);
char*iIndex=strstr(buf,"[");
if(iIndex)
{
sprintf(chTempIp,"%s",iIndex);
intnBuflen=strlen(chTempIp);
for(inti=0;i<nBuflen;i++)
{
chIP[i]=chTempIp[i+1];
if(chTempIp[i]==']')
{
chIP[i-1]='\0';
DeleteFile("c:\\1.ini");
continue;
}
}
}
}
MessageBox(chIP);
C实现获取外网IP:
#include<afxinet.h>
voidCLanChatDlg::GetNetIP()
{
SetDlgItemText(IDC_NET_IP,"正在获取外网IP");
CStringstrsource;
CStringAddress;
CInternetSessionmySession(NULL,0);
CHttpFile*myHttpFile=NULL;
Address="http://www.ip138.com/ip2city.asp";//ip138网页
myHttpFile=(CHttpFile*)mySession.OpenURL(Address);//读取网络地址
while(myHttpFile->ReadString(strsource))
{//循环读取下载来的网页文本
//AddToLog(strsource);
intbegin=0;
begin=strsource.Find("[",0);
if(begin!=-1)//如果找到"[",则找"]"中括号内的文本则是你的外网ip
{intend=strsource.Find("]");
m_internetip=strsource.Mid(begin+1,end-begin-1);//提取外网ip
SetDlgItemText(IDC_NET_IP,m_internetip);//在左下角显示外网ip
}
}
这两个示例都是通过ip138网站来查询外网IP的,感兴趣的读者也可以根据自己的喜好改动一下代码,使之更加完善。