我想将主机名(计算机名我的电脑->属性->高级系统设置->计算机名)转换为IP地址。
有什么方法可以将主机名转换为 IP 地址? 我试过以下但 pHostInfo 为 NULL。 主机名是我的计算机名称。
struct hostent* pHostInfo;
pHostInfo = gethostbyname(hostname);
在上面的代码中,它是 NULL。能否给我将主机名转换为 IP 地址的代码?
最佳答案
#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 {};
}
关于c++ - Windows套接字编程中主机名的IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9400756/