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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值