【问题标题】:Obtaining the IP address of a local machine based on computer name using Win32 Network API使用 Win32 Network API 根据计算机名获取本地机器的 IP 地址
【发布时间】:2011-06-07 13:46:13
【问题描述】:

我正在查找 http://www.codeproject.com/KB/cs/network.aspx(如何获取机器的 IP 地址),它提到 “在 Win32 API 中,这可以使用 NetWork API 来完成。”

我希望通过 C++ 使用此 API 来查找机器的 IP 地址。我在网络上有本地计算机的名称。我试过在 MSDN 上查找它,但只找到“网络管理”API,它似乎没有我需要的功能。我假设我可以使用 Win Socks 来解决这个问题,但对于应该很简单的事情来说,这似乎需要大量的工作。

任何帮助表示赞赏。

编辑:应该提到我说的是本地 IP 地址,而不是外部的。

【问题讨论】:

    标签: c++ winapi networking ip-address


    【解决方案1】:

    你可以使用gethostbyname函数

    检查此示例

    #include <netdb.h>
    #include <arpa/inet.h>
    #include <iostream>
    
    int main()
    {
      const char* const host = "thecomputername" ;
      const hostent* host_info = 0 ;
      host_info = gethostbyname(host) ;
    
      if(host_info)
      {
        std::cout << "host: " << host_info->h_name << '\n' ;
    
        for( int i=0 ; host_info->h_addr_list[i] ; ++i )
        {
          const in_addr* address = (in_addr*)host_info->h_addr_list[i] ;
          std::cout << " address: " << inet_ntoa( *address ) << '\n' ;
        }
      }
      else herror( "error" ) ;
    }
    

    【讨论】:

      【解决方案2】:

      您可以在IP Helper API 中使用GetAdapterAddresses 在本地执行此操作。

      GetAdaptersAddresses 函数 检索相关的地址 与本地适配器 电脑。

      【讨论】:

        猜你喜欢
        • 2011-06-14
        • 2010-09-12
        • 2019-04-26
        • 2012-09-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多