Windows异步非阻塞获取局域网主机名及IP
网络初始化:
WSADATA wsaData = { 0 };
WSAStartup(MAKEWORD(2, 2), &wsaData);
...
WSACleanup();
异步获取局域网主机名代码实现:(支持XP、2003、Vista、Win7、Win8、Win10系统)
BEGIN_MESSAGE_MAP(CScanHostDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_CLOSE()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_MESSAGE(WM_USER_ADD_LIST, OnUserAddList)
END_MESSAGE_MAP()
void GetHostNameByIpAddr(HWND hWnd, int nID, const std::string& ip = "192.168.1.40")
{
in_addr inaddr = { 0 };
inaddr.s_addr = inet_addr(ip.c_str());
BYTE* pByte = new BYTE[MAXGETHOSTSTRUCT];
HANDLE hHandle = WSAAsyncGetHostByAddr(hWnd, nID, (const char*)&inaddr, sizeof(inaddr), AF_INET, (char*)pByte, MAXGETHOSTSTRUCT);
SetProp(hWnd, CUtils::A_To_T(std::to_string((uint64_t)hHandle)).c_str(), (HANDLE)pByte);
return;
}
LRESULT CScanHostDlg::OnUserAddList(WPARAM wParam, LPARAM lParam)
{
int h = WSAGETASYNCBUFLEN(lParam);
int l = WSAGETSELECTERROR(lParam);
HANDLE hHandle = (HANDLE)wParam;
BYTE* pByte = (BYTE*)GetProp(this->m_hWnd, CUtils::A_To_T(std::to_string((uint64_t)hHandle)).c_str());
switch (l)
{
case ERROR_SUCCESS:
{
int i = 0;
in_addr inaddr = { 0 };
struct hostent* pht = (struct hostent*)pByte;
std::cout << pht->h_name << std::endl;
for (char** pAlias = pht->h_aliases; *pAlias != 0; pAlias++)
{
printf("\tAlternate name: %s\n", *pAlias);
}
while (pht->h_addr_list[i] != 0)
{
inaddr.s_addr = *(u_long*)pht->h_addr_list[i++];
printf("\tIPv4 Address #%d: %s\n", i, inet_ntoa(inaddr));
}
}
break;
case WSANO_DATA:
{
}
break;
default:
break;
}
delete pByte;
pByte = nullptr;
RemoveProp(this->m_hWnd, CUtils::A_To_T(std::to_string((uint64_t)hHandle)).c_str());
return 0;
}