zoukankan      html  css  js  c++  java
  • 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. }  
     
  • 相关阅读:
    接口与实现分离
    C++的explicit关键字
    C++的类型转换
    使用catch做单元测试简介
    C++可调用对象与函数表
    在sublime中使用cppcheck
    你需要的代码静态检查
    构造析构与拷贝赋值那些事
    c++的关联容器入门(map and set)
    【致敬程序猿】
  • 原文地址:https://www.cnblogs.com/killer-xc/p/6609898.html
Copyright © 2011-2022 走看看