基础知识
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源)