windows下C++获取本机IP地址列表,本机时间,程序运行路径
获取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;
memset(&hints, 0, sizeof(struct addrinfo));
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
return MYRESULT::WSASTARTUP_ERROR;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
hints.ai_protocol = 0;
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(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;
}