【MFC】获取公网IP地址

// 获取电脑IP地址
CString CDataIO::GetIP()
{    
	// 获取公网ip地址
	HINTERNET hInternet = InternetOpen(L"Microsoft Internet Explorer", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
	if (hInternet == NULL)
	{
		// 打开网络会话失败
		return _T("");
	}

	HINTERNET hConnect = InternetOpenUrl(hInternet, L"http://whois.pconline.com.cn/ipJson.jsp?json=true", NULL, 0, INTERNET_FLAG_RELOAD, 0);
	if (hConnect == NULL)
	{
		// 打开URL失败
		InternetCloseHandle(hInternet);
		return _T("");
	}

	char buffer[4096] = { 0 };
	DWORD bytesRead;
	CString data;
	BOOL bRet;
	while (TRUE)
	{
		bRet = InternetReadFile(hConnect, buffer, sizeof(buffer), &bytesRead);
		if (!bRet || (0 == bytesRead))
			break;
		buffer[bytesRead] = '\0';
		data.Append(CA2T(buffer), bytesRead);
	}
	InternetCloseHandle(hConnect);
	InternetCloseHandle(hInternet);

	// 去除前后换行符号
	data = data.Trim();
	// 解析JSON数据
	CString ip, address;

	int pos1 = data.Find(_T("\"ip\":\"")) + 5;
	int pos2 = data.Find(_T("\""), pos1 + 1);
	ip = data.Mid(pos1 + 1, pos2 - pos1 - 1);

	pos1 = data.Find(_T("\"addr\":\"")) + 7;
	pos2 = data.Find(_T("\""), pos1 + 1);
	address = data.Mid(pos1 + 1, pos2 - pos1 - 1);

	CString strIP;
	strIP.Format(_T("IP:%s Addr:%s"), ip, address);

	return strIP;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值