c++ - Windows套接字编程中主机名的IP地址

标签 c++ c sockets winsock

我想将主机名(计算机名我的电脑->属性->高级系统设置->计算机名)转换为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/

相关文章:

Java - 有没有一种方法可以让客户端和服务器通过 IPv4 连接而无需端口转发?

c++ - const 迭代器的模板参数而不是迭代器

c++ - 将 uint8_t 类型写入文件 C++

c++ - 如何创建自定义组件?访问私有(private)字段时出错

c - 在 opencv 序列中需要帮助!

c - 使用参数打开套接字

Java套接字: how to skip reading line from server when no output is sent from the server

c++ - 运行时绑定(bind)和虚拟继承

c++ - 奇怪的程序挂起,这在调试中意味着什么?

c++ - 从 C++ 宏创建字符串列表和枚举列表