Windows套接字编程中从主机名获取IP地址

Nee*_*tel 3 c c++ sockets winsock

我想将主机名(计算机名我的电脑->属性->高级系统设置->计算机名)转换为IP地址。

有什么办法可以将主机名转换为IP地址吗?我尝试过以下操作,但 pHostInfo 为 NULL。主机名是我的计算机名称。

struct hostent* pHostInfo;
pHostInfo = gethostbyname(hostname);
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,它是 NULL。您能给我将主机名转换为 IP 地址的代码吗?

Ole*_*lov 5

#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 {};
}
Run Code Online (Sandbox Code Playgroud)