从主机名在Windows套接字编程中的IP地址
问题描述:
我想将主机名(计算机名我的电脑 - >属性 - >高级系统设置 - >计算机名)转换为IP地址。从主机名在Windows套接字编程中的IP地址
有什么办法可以将主机名转换为IP地址? 我试过以下,但pHostInfo来作为NULL。 和主机名是我的电脑名称。
struct hostent* pHostInfo;
pHostInfo = gethostbyname(hostname);
在上面的代码中它来到NULL。你可以请给我代码,将主机名转换为IP地址?
答
使用gethostname()
获取本地主机名。然后您可以将其传递给gethostbyname()
。
但是,请注意,gethostbyname()
对本地主机执行DNS查找,因此可能获得实际上不属于本地计算机的IP地址,或者如果DNS配置错误,则可能获得无效IP。
如果您真正想要的是获取本地计算机的IP地址,请改为使用GetAdaptersInfo()
或GetAdaptersAddresses()
。
答
检查getaddrinfo
功能!如果您在Windows XP SP2(或更高版本)上查找IPv6地址,则应使用GetAddrInfoW
函数。这两个函数在文档中都有示例。如果您使用的是IPv4和/或MS Vista以及更好的版本,则应该选择getaddrinfo
,因为它与平台无关(POSIX.1-2001)。
答
#include <string>
#include <netdb.h>
#include <arpa/inet.h>
std::string HostToIp(const std::string& host) {
hostent* hostname = gethostbyname(host.c_str());
if(hostname)
return std::string(inet_ntoa(**(in_addr**)hostname->h_addr_list));
return {};
}
'WSAGetLastError()'告诉你什么? – 2012-02-22 18:41:03