通过 URL 获取 IP 地址

Kri*_*vić 0 c sockets network-programming tcp

这有效

target.sin_addr.s_addr = inet_addr("127.0.0.1");
Run Code Online (Sandbox Code Playgroud)

但我想输入网站 URL 中的 IP

我努力了

const char host[] = "http://www.google.com/";
struct hostent *host_ip;
host_ip = gethostbyaddr(host, strlen(host), 0);
Run Code Online (Sandbox Code Playgroud)

在我使用 gethostbyaddr() 之前,我确实做了 WSAStartup;

我试过这个

target.sin_addr.s_addr = inet_addr(host_ip);
Run Code Online (Sandbox Code Playgroud)

我也尝试过一些类似的方法,但都不起作用。有人可以告诉我如何正确执行此操作吗?

谢谢你!

编辑:

当我做

host_ip = gethostbyaddr((char *)&host, strlen(host), 0);
std::cout << host_ip->h_addr;
Run Code Online (Sandbox Code Playgroud)

它给了我

httpa104-116-116-112.deploy.static.akamaitechnologies.com
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 5

inet_addr()接受 IPv4 地址字符串作为输入并返回该地址的二进制表示形式。在这种情况下,这不是您想要的,因为您没有 IP 地址,而是有主机名。

使用 ,您走在正确的轨道上gethostby...(),但您需要使用gethostbyname()(lookup by hostname) 而不是gethostbyaddr()(lookup by IP address) 1。并且您无法将完整的 URL 传递给它们中的任何一个。 gethostbyname()仅接受主机名作为输入,因此您需要解析 URL 并提取其主机名,然后您可以执行以下操作:

const char host[] = ...; // an IP address or a hostname, like "www.google.com" by itself
target.sin_addr.s_addr = inet_addr(host);
if (target.sin_addr.s_addr == INADDR_NONE)
{
    struct hostent *phost = gethostbyname(host);
    if ((phost) && (phost->h_addrtype == AF_INET))
        target.sin_addr = *(in_addr*)(phost->h_addr);
    ...
}
else
    ...
Run Code Online (Sandbox Code Playgroud)

1顺便说一句,gethostby...() 函数已弃用,请使用getaddrinfo()getnameinfo()代替。

const char host[] = ...; // an IP address or a hostname, like "www.google.com" by itself

addrinfo hints = {0};
hints.ai_flags = AI_NUMERICHOST;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

addrinfo *addr = NULL;

int ret = getaddrinfo(host, NULL, &hints, &addr);
if (ret == EAI_NONAME) // not an IP, retry as a hostname
{
    hints.ai_flags = 0;
    ret = getaddrinfo(host, NULL, &hints, &addr);
}
if (ret == 0)
{
    target = *(sockaddr_in*)(addr->ai_addr);
    freeaddrinfo(addr);
    ...
}
else
    ...
Run Code Online (Sandbox Code Playgroud)