c++ 获取本地ip和外网ip

// ctest.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include<stdio.h>
#include <urlmon.h>
#define MAX_SIZE 1024
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib,"ws2_32.lib")

#include<windows.h>
#include <atlstr.h>

#define IP "116.21.41.124"

//#define _CRT_SECURE_NO_WARNINGS

using namespace std;

//内网IP
int 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 WSAGetLastError();
	}

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



//外网IP
static char * WIP = new char[MAX_PATH];
int GetInternetIP()
{
//	CoInitialize(NULL);
	char buf[MAX_PATH] = { 0 };    //把网页中读出的数据放在此处
	char chTempIp[128] = { 0 };
	char chIP[64] = { 0 };        //最终存放IP在此
								  //将网页数据写入c:\i.ini文件中

	CString pURL = "https://api.ip.sb/ip";
	CString pFileName = "D:\\a.html";
//	DeleteUrlCacheEntry((LPCWSTR)pURL);
	if (URLDownloadToFile(0, pURL, pFileName, 0, NULL) == S_OK)
	{
		printf("URLDownloadToFile OK\n");
	}
	else
	{
		printf("URLDownloadToFile Fail,Error:%d\n", GetLastError());
	}
	FILE *fp = fopen("D:\\a.html", "r");
	if (fp != NULL)
	{
		fseek(fp, 0, SEEK_SET);
		fread(buf, 1, MAX_PATH, fp);
		fclose(fp);
	}

	cout << strlen(buf) << endl;
	memcpy(WIP, buf,strlen(buf) - 1);
	WIP[strlen(buf) - 1] = 0;
//	WIP = buf;

	printf("外网IP: %s\n", WIP);
	remove("D:\\a.html");
//	CoUninitialize();
	return 0;
}

int main()
{
//	GetLocalIP();
	GetInternetIP();
	cout << WIP << endl;
	if (strcmp(WIP, IP) == 0)
	{
		cout << "ip 验证通过 服务器启动" << endl;
	}
	else
	{
		cout << "ip 验证不通过 请找管理员解决" << endl;
		system("pause");
		return 0;
	}

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值