C++:gethostname,gethostbyname获取IP地址和计算机名

使用gethostname()和gethostbyname()获取IP地址和计算机名,记录一下,省得老忘。

 

[cpp] view plain copy
 
  1. int CNetTestDlg::GetLocalHostName( CString& sHostName )     // 获取机器名  
  2. {  
  3.  char szHostName[256];  
  4.  int nRetCode;  
  5.  nRetCode = gethostname(szHostName, sizeof(szHostName));  
  6.  if (nRetCode != 0)  
  7.  {  
  8.   memcpy(szHostName, ("Not Available"), sizeof("Not Available"));  
  9.   return WSAGetLastError();  
  10.  }  
  11.  sHostName = szHostName;  
  12.  return 0;  
  13. }  


 

[cpp] view plain copy
 
    1. int CNetTestDlg::GetIPAddress(const CString& sHostName, CString& sIPAddress)    // 获取IP地址  
    2. {  
    3.  struct hostent *lpHostEnt = gethostbyname(sHostName);  
    4.  if (lpHostEnt == NULL)  
    5.  {  
    6.   sIPAddress = "";  
    7.   return WSAGetLastError();  
    8.  }  
    9.  LPSTR lpAddr = lpHostEnt->h_addr;  
    10.  if (lpAddr)  
    11.  {  
    12.   struct in_addr inAddr;  
    13.   memmove(&inAddr, lpAddr, 4);      // 将地址进行转换成常规形式  
    14.   sIPAddress = inet_ntoa(inAddr);  
    15.   if (sIPAddress.IsEmpty())  
    16.   {  
    17.    sIPAddress = "Not available";  
    18.   }  
    19.  }  
    20.  return 0;  
    21. }  
 

posted on 2017-03-24 09:57  humbird  阅读(974)  评论(0编辑  收藏  举报

导航