当前位置:网站首页>MFC obtains local IP (used more in network communication)

MFC obtains local IP (used more in network communication)

2022-04-23 19:29:00 ToneChip

CString CUDPDlg::GetIP()    // Access to the local IP
{
	WORD wVersionRequested;
	WSADATA wsaData;
	char name[255];    //  Local hostname array variable 
	CString m_ip;      // IP Address string variable 
	PHOSTENT hostinfo;  // hostent Structure pointer 
	wVersionRequested = MAKEWORD(2, 0);   // Connecting applications to winsock Dll
	if (WSAStartup(wVersionRequested, &wsaData) == 0)
	{
		if (gethostname(name, sizeof(name)) == 0)  // Get the local host name 

		{
			if ((hostinfo = gethostbyname(name)) != NULL) // Get host information 
			{
				m_ip = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list); // Convert to get IP Address 
			}
			else m_ip = "IP Detection failed ";
		}
		WSACleanup();   //  suspend winsock DLL Use 
	}
	return m_ip;  // return IP Address string 
}

Call the following

	CString localIP;
	localIP = GetIP();   // Get this machine IP
	SetDlgItemText(IDC_IP1, localIP);	// Get local IP Display to the interface 

版权声明
本文为[ToneChip]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231923488465.html