ネイティブネットワーク、外部ネットワークip(C++)の取得

2124 ワード

  • 基礎知識
  • コンピュータはローカルエリアネットワーク内にあり、ゲートウェイ/ルータを介してインターネットに接続するとipはイントラネットip、アウターネットipに分けられる.ipconfigで得られたのはローカルエリアネットワークipである.
  • パソコン直接ダイヤル接続などは、本機が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