简体   繁体   English

使用Win32 Network API根据计算机名称获取本地计算机的IP地址

[英]Obtaining the IP address of a local machine based on computer name using Win32 Network API

I was looking up http://www.codeproject.com/KB/cs/network.aspx (How to get the IP address of a machine) and it mentions that "In the Win32 API this could be accomplished using the NetWork API." 我正在查找http://www.codeproject.com/KB/cs/network.aspx (如何获取计算机的IP地址),其中提到“在Win32 API中,可以使用NetWork API来完成。 “

I wish to use this API using C++ in order to find the IP address of a machine. 我希望使用C ++使用此API来查找计算机的IP地址。 I have the local computer's name on the network. 我在网络上有本地计算机的名称。 I've tried looking it up on MSDN but only found the "Network Management" API and it doesn't appear to have the functions I need. 我尝试在MSDN上查找它,但只找到“网络管理” API,它似乎没有我需要的功能。 I'm assuming I could use Win Socks to figure this out but it seems like a large amount of work for something which should be simple. 我以为我可以使用Win Socks来解决这个问题,但是似乎很容易完成一些工作。

Any help appreciated. 任何帮助表示赞赏。

EDIT: Should mention that I am talking about the local IP address, not external. 编辑:应该提到我说的是本地IP地址,而不是外部。

you can use the gethostbyname function 您可以使用gethostbyname函数

check this sample 检查这个样本

#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" ) ;
}

You can do this locally using GetAdapterAddresses in the IP Helper API . 您可以使用IP Helper API中的GetAdapterAddresses在本地执行此操作。

The GetAdaptersAddresses function retrieves the addresses associated with the adapters on the local computer. GetAdaptersAddresses函数检索与本地计算机上的适配器关联的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM