c++ 获取外网ip地址

来源:互联网 发布:饥荒巨人的统治mac版 编辑:程序博客网 时间:2024/05/20 04:50

// 外部调用 ==============================================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 1024getnetworkip::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;}


0 0
原创粉丝点击