2011-01-12 217 views
0

我正在查找http://www.codeproject.com/KB/cs/network.aspx(如何获取计算机的IP地址),并提及“在Win32 API中,可以使用NetWork API“。使用Win32网络API获取基于计算机名称的本地计算机的IP地址

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

任何帮助表示赞赏。

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

回答

3

可以使用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") ; 
} 
相关问题