主要是两个函数的使用,gethostname();、gethostbyname();
自定义两个函数GetLocalHostName获取计算机名、GetIPAddress获取IP地址
1 int CIPDlg::GetLocalHostName(CString &strHostName) 2 { 3 char szHostName[256]; 4 int nRetCode; 5 nRetCode = gethostname(szHostName, sizeof(szHostName)); 6 if(nRetCode != 0) 7 { 8 strHostName = _T("Not available"); 9 return WSAGetLastError(); 10 } 11 strHostName = szHostName; 12 return 0; 13 }
1 int CIPDlg::GetIPAddress(const CString &strHostName, CString &strIPAddress) 2 { 3 struct hostent FAR *lpHostEnt = gethostbyname(strHostName); 4 if(lpHostEnt == NULL) 5 { 6 strIPAddress = _T(""); 7 return WSAGetLastError(); 8 } 9 LPSTR lpAddr = lpHostEnt->h_addr_list[0]; 10 if(lpAddr) 11 { 12 struct in_addr inAddr; 13 memmove(&inAddr, lpAddr, 4); 14 strIPAddress = inet_ntoa(inAddr); 15 if(strIPAddress.IsEmpty()) 16 { 17 strIPAddress = _T("Not avilable"); 18 } 19 } 20 return 0; 21 }