本文以C與MFC的兩個實例詳述了取外網IP的兩種實現方法,具體實現代碼如下:
MFC語言實現獲取外網IP:
# include <windows.h># include <urlmon.h># pragma comment(lib,"URLMON.lib")void main(){ URLDownloadToFile(NULL,"http://www.ip138.com/ip2city.asp","ip.txt",0,NULL); system("notepad ip.txt");}#include<urlmon.h>#pragma comment (lib,"Urlmon.lib")char buf[MAX_PATH] = {0};char chTempIp[128];char chIP[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); int nBuflen = strlen(chTempIp);for(int i =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>void CLanChatDlg::GetNetIP(){SetDlgItemText(IDC_NET_IP,"正在獲取外網IP");CString strsource;CString Address;CInternetSession mySession(NULL,0);CHttpFile* myHttpFile=NULL;Address="http://www.ip138.com/ip2city.asp";//ip138網頁myHttpFile=(CHttpFile*)mySession.OpenURL(Address);//讀取網絡地址while(myHttpFile->ReadString(strsource)){ //循環讀取下載來的網頁文本 // AddToLog(strsource); int begin=0; begin=strsource.Find("[",0); if(begin!=-1)//如果找到"[", 則找"]" 中括號內的文本則是 你的外網ip { int end=strsource.Find("]"); m_internetip=strsource.Mid(begin+1,end-begin-1);//提取外網ip SetDlgItemText(IDC_NET_IP,m_internetip);//在左下角顯示外網ip }}
這兩個示例都是通過ip138網站來查詢外網IP的,感興趣的讀者也可以根據自己的喜好改動一下代碼,使之更加完善。
新聞熱點
疑難解答
圖片精選