工控编程吧
标题: 上位机MFC如何通过主机名称获得IP地址 [打印本页]
作者: qq263946146 时间: 2019-8-6 11:19
标题: 上位机MFC如何通过主机名称获得IP地址
- //初始化WinSock
- WSADATA WSAData;
- if (WSAStartup(MAKEWORD(2,0), &WSAData) != 0)
- {
- return;
- }
-
- //获得本地计算机主机名称
- CString strName = _T("");
- gethostname(strName.GetBuffer(1024), 1024);
- strName.ReleaseBuffer();
- //获得主机信息
- struct hostent* pHostEnt = gethostbyname(strName);
- if (pHostEnt == NULL)
- {
- return;
- }
- //获得主机IP地址
- CString strText = _T("");
- strText.Format(_T("%s的IP地址:\n"), strName);
- int n = 0;
- while (pHostEnt->h_addr_list[n] != NULL)
- {
- CString strTemp = _T("");
- strTemp.Format(_T("%d.%d.%d.%d\n"),
- (pHostEnt->h_addr_list[n][0] & 0x00FF),
- (pHostEnt->h_addr_list[n][1] & 0x00FF),
- (pHostEnt->h_addr_list[n][2] & 0x00FF),
- (pHostEnt->h_addr_list[n][3] & 0x00FF));
- strText += strTemp;
- n++;
- }
- AfxMessageBox(strText);
- //清理WinSock
- WSACleanup();
复制代码
(, 下载次数: 3)