我是靠谱客的博主 诚心外套,这篇文章主要介绍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. }  
 

转载于:https://www.cnblogs.com/killer-xc/p/6609898.html

最后

以上就是诚心外套最近收集整理的关于C++:gethostname,gethostbyname获取IP地址和计算机名的全部内容,更多相关C++:gethostname内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部