NetCardInfo.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include "NetCardInfo.h"
  2. #include <stdio.h>
  3. #include <ifaddrs.h>
  4. #include <arpa/inet.h>
  5. #include <string>
  6. using namespace std;
  7. class CNetCardInfoImpl
  8. {
  9. public:
  10. CNetCardInfoImpl();
  11. ~CNetCardInfoImpl();
  12. void Init();
  13. void GetNetCardIp(std::set<std::string>& IPVector);
  14. private:
  15. struct ifaddrs* m_pIpAdapterInfo;//getifaddrs()创建的链表上的数据结构
  16. bool m_bSuccess;
  17. };
  18. CNetCardInfoImpl::CNetCardInfoImpl():m_pIpAdapterInfo(NULL), m_bSuccess(false)
  19. {
  20. }
  21. CNetCardInfoImpl::~CNetCardInfoImpl()
  22. {
  23. if (m_pIpAdapterInfo)
  24. {
  25. freeifaddrs(m_pIpAdapterInfo);
  26. }
  27. m_bSuccess = false;
  28. }
  29. void CNetCardInfoImpl::Init()
  30. {
  31. if (m_pIpAdapterInfo)
  32. {
  33. freeifaddrs(m_pIpAdapterInfo);
  34. }
  35. m_bSuccess = false;
  36. int nRet = getifaddrs(&m_pIpAdapterInfo);//获取本地网络接口的信息。
  37. if (nRet < 0)
  38. {
  39. return;
  40. }
  41. m_bSuccess = (0 == nRet)?true:false;
  42. }
  43. void CNetCardInfoImpl::GetNetCardIp(std::set<std::string>& IPVector)
  44. {
  45. if (m_bSuccess)
  46. {
  47. struct sockaddr_in *sin = NULL;
  48. struct ifaddrs *ifa = NULL;
  49. struct ifaddrs *ifList = m_pIpAdapterInfo;
  50. for (ifa = ifList; ifa != NULL; ifa = ifa->ifa_next)//循环获取网口IP
  51. {
  52. if(ifa->ifa_addr->sa_family == AF_INET)
  53. {
  54. sin = (struct sockaddr_in *)ifa->ifa_addr;
  55. string strIp(inet_ntoa(sin->sin_addr));
  56. IPVector.insert(strIp);
  57. }
  58. }
  59. }
  60. }
  61. CNetCardInfo::CNetCardInfo()
  62. {
  63. m_pImpl = new CNetCardInfoImpl;
  64. }
  65. CNetCardInfo::~CNetCardInfo()
  66. {
  67. if (m_pImpl)
  68. {
  69. delete m_pImpl;
  70. m_pImpl = NULL;
  71. }
  72. }
  73. void CNetCardInfo::Init()
  74. {
  75. if (m_pImpl)
  76. {
  77. m_pImpl->Init();
  78. }
  79. }
  80. void CNetCardInfo::GetNetCardIp(std::set<std::string>& IPVector)
  81. {
  82. if (m_pImpl)
  83. {
  84. m_pImpl->GetNetCardIp(IPVector);
  85. }
  86. }