1. 程式人生 > >c++ 獲取外網ip地址

c++ 獲取外網ip地址

// 外部呼叫 ==============================================
networkip.GetLocalIP();
string retip = networkip.GetInternetIP();

// 封裝實現 ==============================================
class getnetworkip
{
public:
getnetworkip();
~getnetworkip();

std::string GetLocalIP();
std::string GetInternetIP();
private:
};

//////////////////////////////////////////////////////////////////////////
#include <WINSOCK2.H>
#include <urlmon.h>
#include <string> 
using namespace std;


#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "urlmon.lib")

#define MAX_SIZE 1024

getnetworkip::getnetworkip()
{
}

getnetworkip::~getnetworkip()
{
}

std::string getnetworkip::GetLocalIP()
{
WSADATA wsaData;
int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
if (err != 0)
{
return "err";
}

char szHostName[MAX_PATH] = { 0 };
int nRetCode;
nRetCode = gethostname(szHostName, sizeof(szHostName));

char* lpLocalIP;
PHOSTENT hostinfo;

if (nRetCode != 0)
{
return "errcode";
}

hostinfo = gethostbyname(szHostName);
lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);

if (szHostName != NULL)
{
printf("主機名: %s\n", szHostName);
printf("本地IP: %s\n", lpLocalIP);
}

WSACleanup();

return lpLocalIP;
}

std::string getnetworkip::GetInternetIP()
{
char buf[2048] = { 0 };    //把網頁中讀出的資料放在此處
char chURL[128] = { "http://www.whatismyip.com.tw/" };

//將網頁資料寫入c:\i.ini檔案中
URLDownloadToFileA(0, chURL, "c:\\i.ini", 0, NULL);

string str_ip("");
FILE *fp = fopen("c:\\i.ini", "rb+");
if (fp != NULL)
{
//
fseek(fp, 0, SEEK_SET);
fread(buf, 2048, 1, fp);
fclose(fp);

//在buf中查詢 [ 的位置, iIndex是buf中從[開始剩下的字串,包括[這個字串 == 
string str = buf;
int nstart = str.find("<h2>");
int nend = str.find("</h2>");
int lenth = nend - nstart - 4;

str_ip = str.substr(nstart + 4, lenth);
}

remove("c:\\i.ini");

return str_ip;
}