// 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;
}
c++ 获取本地ip和外网ip
最新推荐文章于 2021-01-15 10:52:52 发布