MFC C++ 获取外网IP地址

#include <afxinet.h>

//GB2312 转换成 Unicode
wchar_t* GB2312ToUnicode(const char* szGBString)
{
    UINT nCodePage = 936; //GB2312

    int nLength=MultiByteToWideChar(nCodePage,0,szGBString,-1,NULL,0);

    wchar_t* pBuffer = new wchar_t[nLength+1];

    MultiByteToWideChar(nCodePage,0,szGBString,-1,pBuffer,nLength);

    pBuffer[nLength]=0;

    return pBuffer;
}

CString CNetDlg::GetNetIp()
{
    CString internetIp = _T("");

    char chSource[4096] = {0};
    CString strAddress;
    CInternetSession mySession(NULL,0);
    CHttpFile* myHttpFile=NULL;

    strAddress = _T("http://20140507.ip138.com/ic.asp");//ip138网页

    TRY
    {
        myHttpFile = (CHttpFile*)mySession.OpenURL(strAddress);//读取网络地址

        while(myHttpFile->Read(chSource, 4096))
        {
            //循环读取下载来的网页文本
            int begin = 0;

            // 目前只处理字符集为gb2312的情况
            begin = CKMP<BYTE*>::Find((BYTE*)chSource, strlen(chSource), (BYTE*)_C("charset=gb2312"), 14);
            
            if (begin != -1)
            {
                WCHAR* wchSource = GB2312ToUnicode(chSource);
                internetIp = wchSource;
                delete[] wchSource;
            }

            begin = internetIp.Find(_T("["), 0);

            if(begin !=- 1)//如果找到"[", 则找"]"  中括号内的文本则是 你的外网ip
            { 
                int end=internetIp.Find(_T("]"));

                internetIp = internetIp.Mid(begin+1, end-begin-1);//提取外网ip

                break;
            }
        }

        myHttpFile->Close();

        mySession.Close();
    }
    CATCH(CInternetException,e)
    {
        internetIp.Format(T_T(_$_STRING_FORMAT_1), e->m_dwError, e->m_dwContext);
    }
    CATCH_ALL(e)
    {
        TCHAR ch[MAX_PATH] = {0};
        e->GetErrorMessage(ch, MAX_PATH);
        internetIp.Format(T_T(_$_STRING_FORMAT_1), -3, ch);
    }
    END_CATCH_ALL

    TRACE(internetIp);

    return internetIp;
}


参考:

http://blog.csdn.net/cbk861110/article/details/7844729


网页地址

http://20140507.ip138.com/ic.asp

http://www.ip138.com

的网页源码中查找到。

<tr><td align="center"><h3>www.ip138.com IP查询(搜索IP地址的地理位置)</h3></td></tr>
	<tr>
		<td height="30" align="center" valign="top"><iframe src="http://20140507.ip138.com/ic.asp" rel="nofollow" frameborder="0" scrolling="no" width="100%" height="100%"></iframe></td>
	</tr>

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值