【问题标题】: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" ) ;
}