獲取本機內網、外網ip(C++)<轉>


  • 基礎知識

 

  1.  電腦在局域網內,通過網關/路由器連接到Internet則ip分為內網ip、外網ip。通過ipconfig得到的為局域網ip。
  2. 電腦直接撥號連接等,則本機通過ipconfig得到的就是外網ip。

 

  • 代碼
//Get IP
int GetLocalIP(std::string &local_ip);
int GetInternetIP(std::string &Inernet_ip);
int GetLocalIP( std::string &local_ip )
{
    WSADATA wsaData = {0};
    if (WSAStartup(MAKEWORD(2, 1), &wsaData) != 0)
        return kErrorWSAStartup;
    char szHostName[MAX_PATH] = {0};
    int nRetCode;
    nRetCode = gethostname(szHostName, sizeof(szHostName));
    PHOSTENT hostinfo;
    if (nRetCode != 0)
        return WSAGetLastError();        
    hostinfo = gethostbyname(szHostName);
    local_ip = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);
    WSACleanup();
    return 1;
}
 
int GetInternetIP( std::string &Inernet_ip )
{
    Inernet_ip.resize(32);
    TCHAR szTempPath[_MAX_PATH] = {0}, szTempFile[MAX_PATH] = {0};
    std::string buffer;
    GetTempPath(MAX_PATH, szTempPath);
    UINT nResult = GetTempFileName(szTempPath, _T("~ex"), 0, szTempFile);
    int ret=URLDownloadToFile(NULL,_T("http://www.ip138.com/ip2city.asp"),szTempFile,BINDF_GETNEWESTVERSION,NULL);
    if (ret == S_FALSE)
        return 0;
    FILE *fp;
    if (_wfopen_s(&fp,szTempFile,_T("rb"))!=0){
        return 0;
    }
    fseek(fp,0,SEEK_END);//得到文件大小
    int ilength=ftell(fp);
    fseek(fp,0,SEEK_SET);
    if(ilength>0)
    { 
        buffer.resize(ilength);
        fread(&buffer[0],sizeof(TCHAR),ilength,fp);
        fclose(fp);
        DeleteFile(_T("ip.ini"));
        
         char* str_ip = strstr(&buffer[0], "[");
         if (str_ip !=NULL)
         {
             sscanf_s(str_ip+1, "%[^]]", &Inernet_ip[0], 32);
         }     
        return 1;
    }
    else
    {
        fclose(fp);
        return 0;
    }
}
  • 解釋
獲取內網ip:
1、通過系統函數gethostname得到主機名。
2、通過主機名得到內網ip。
獲取外網ip:
1、通過ip源,下載其腳本文件並保存。
2、保存文件中有外網ip,解析出來。
 

獲取外網ip所需要的IP源:(幾乎所有可以顯示IP地址的網頁都可以成為IP源)

http://www.ipchicken.com/ 

http://whatismyipaddress.com/ 

http://www.ip138.com/ip2city.asp

 

轉載地址:https://blog.csdn.net/xiaolengzile/article/details/41868989

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM