VC--获取本机 局域网IP 和外网IP

#include <Winsock2.h>
//===========================
//    获取本机局域网IP
//===========================
char* GetLocalIP(void)             
{
WSADATA wsaDataqq;
WSAStartup(MAKEWORD(1,1),&wsaDataqq); 
PHOSTENT hostinfo;
char name[512] = {0};
in_addr dest;
char *ipAddr=NULL;


if(gethostname (name,sizeof(name)) != 0 || (hostinfo = gethostbyname(name)) == NULL)
return NULL;


for(int a=0; hostinfo->h_addr_list[a] != NULL ;a++)
{
    memcpy(&dest, hostinfo->h_addr_list[a], hostinfo->h_length);
    //多个网卡,可在这循环中获取多个ip
    if (a==0){
    ipAddr=inet_ntoa(dest); 
    }
}
    WSACleanup();
    return ipAddr;
}
//===========================
//    获取本机外网IP
//===========================
CString GetInternetIP(){


//两个查询网站供用户切换
#if(1)
    CString checkWeb="http://only-997227-218-13-34-109.nstool.netease.com/";
    CString tagStr="您的IP地址信息: "; 
    CString endChar=" ";
#else
    CString checkWeb="http://www.ip138.com/ips1388.asp";
    CString tagStr="您的IP地址是:["; 
    CString endChar="]";
#endif


    HRESULT hr=URLDownloadToFileA(0, _T(checkWeb),_T("ipFile.txt"), 0,NULL);    
    if (hr!=S_OK){
        return "";
    }

    CFile file;
    file.Open(_T("ipFile.txt"),CFile::modeRead);
    if (!file)
    {
        return "";
    }
    ULONGLONG len=file.GetLength();
    char* buf=new char[len+1];
    ZeroMemory(buf,len+1);
    file.Read(buf,len);
    buf[len]=0;
    CString ans=buf;
    CString ip="";

    int ix=ans.Find(tagStr);
    int endn=-1;
    if (ix>-1)
    {
        len=tagStr.GetLength();
        endn=ans.Find(endChar,ix+len);
        if (endn>-1)
        {
            ip=ans.Mid(ix+len,endn-ix-len);
        }
    }
    delete buf;
    file.Close();
    return ip;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值