获取本机内网、外网ip

本文介绍了如何通过编程手段获取电脑的内网IP和外网IP。对于内网IP,可以通过系统函数gethostname结合gethostbyname实现;对于外网IP,则需要从特定网站下载脚本文件并解析出IP信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值