TOC

获取IP地址

int32_t GetLocalIP(std::vector<std::string>& vdata)
{
	WSADATA wsaData;
	int iResult;
	DWORD dwRetval;
	struct addrinfo* result = nullptr;
	struct addrinfo* ptr = nullptr;
	struct addrinfo hints;
	struct addrinfo* cur = nullptr;
	struct sockaddr_in* pSockaddr;
	int temp = 0;

	//初始化Winsock
	memset(&hints, 0, sizeof(struct addrinfo));
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0)
	{
		return MYRESULT::WSASTARTUP_ERROR;
	}

	//设置hints信息
	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;
	hints.ai_protocol = 0;

	//调用getaddrinfo()如果成功返回地址信息列表
	char hostname[50];
	gethostname(hostname, 50);  //获得主机名称
	dwRetval = getaddrinfo(hostname, nullptr, &hints, &result);  //利用主机名称获取本地地址

	for (cur = result; cur != NULL; cur = cur->ai_next)
	{
		//将本地地址转换成字符串显示
		pSockaddr = (sockaddr_in*)cur->ai_addr;
		char str[INET_ADDRSTRLEN];
		const char* pIP = inet_ntop(AF_INET, &pSockaddr->sin_addr, str, sizeof(str));

		vdata.push_back(pIP);
	}
	
	//清理
	freeaddrinfo(result);
	WSACleanup();
	return MYRESULT::SECCESS;
}

获取运行路径

std::string GetRuningPath()
{
	//获取文件路径
	char szPath[MAX_PATH + 1] = { 0 };

	//GetModuleFileNameA获取文件的绝对路径
	//GetCurrentDirectory当前运行目录的路径(注意这个的结果在某些情况下与GetModuleFileNameA获取的是不同的)
	GetModuleFileNameA(NULL, szPath, MAX_PATH);

	std::string strPath(szPath);

	//删除文件名,只获得路径 字串
	std::size_t lastPos = strPath.rfind('\\');
	if (lastPos == std::string::npos)return "";
	strPath = strPath.substr(0, lastPos);

	return strPath;
}

获取本地时间

std::string GetLocalTime()
{
	std::string time;

	SYSTEMTIME sys;
	GetLocalTime(&sys);

	//将时间转换为字符串,并统一长度
	time = time + std::to_string(sys.wYear) + "-" + std::to_string(sys.wMonth) + "-" + std::to_string(sys.wDay) + " " +
		std::to_string(sys.wHour) + ":" + std::to_string(sys.wMinute) + ":" + std::to_string(sys.wSecond);
	while (time.length() < 19)time = time + " ";

	return time;
}

Q.E.D.