首页 > 代码库 > 如何获取外网IP地址

如何获取外网IP地址

常用手动查询方法是直接查询:http://www.ip138.com/


代码实现方法如下:

方法I:C语言实现

//原理: 通过访问"http://city.ip138.com/ip2city.asp"解析返回内容

#include <urlmon.h>
#pragma comment (lib,"Urlmon.lib")

void GetBigIpAddress(char *szBuff)
{
	if (NULL == szBuff || 0 == strlen(szBuff))
	{
		return;
	}

	//ip138网页
	URLDownloadToFile(0, "http://city.ip138.com/ip2city.asp", "ip.txt", 0, NULL);

	FILE *fp = NULL;
	fopen_s(&fp, "ip.txt", "r");
	char szTmp[MAX_PATH + 1] = { 0 };

	if (NULL != fp)
	{
		fseek(fp, 0, SEEK_SET);
		fread(szTmp, 1, MAX_PATH, fp);
		fclose(fp);

		char* pIndex = strstr(szTmp, "[");
		if (NULL != pIndex)
		{
			sprintf_s(szBuff, MAX_PATH, "%s", pIndex + 1);

			int nBuflen = strlen(szBuff);
			for (int i = 0; i < nBuflen; i++)
			{
				if (szBuff[i] == ']')
				{
					szBuff[i] = '\0';
					break;;
				}
			}
		}
	}

	DeleteFile("ip.txt");
}

方法II:MFC语言实现

原理:通过CInternetSession访问

void GetNetAddress_V2(CString &sIP)
{
	//ip138网页
	CString Address = "http://city.ip138.com/ip2city.asp";

	//读取网络地址
	CInternetSession mySession(NULL, 0);
	CHttpFile* pHttpFile = (CHttpFile*)mySession.OpenURL(Address);
	if (NULL == pHttpFile)
	{
		return;
	}

	//循环读取下载来的网页文本
	CString sContent = "";
	while (pHttpFile->ReadString(sContent))
	{ 
		int nBegin = sContent.Find("[", 0);

		if (-1 != nBegin)
		{
			int nEnd = sContent.Find("]");
			sIP = sContent.Mid(nBegin + 1, nEnd - nBegin - 1);
		}
	}
}


如何获取外网IP地址